首页 > 解决方案 > 在 C# String 构造函数 String(Char*) 中,为什么构造函数不期望指向字符数组的指针?

问题描述

我使用 C# 已经好几年了,但从未在 C# 中使用过指针。我正在使用 String API,但我不知道为什么 char* 实际上是一个数组而不是单个字符。

API定义:

[System.CLSCompliant(false)]
public String (char* value);

API 文档的片段:

参数

价值 Char*

指向以空字符结尾的 Unicode 字符数组的指针。


声明char* singleChar是指向单个字符的指针吗?指针文档示例似乎是这样说的。

那么,为什么/如何它也可以是指向数组的指针?为什么不是参数类型char[]*

标签: c#.netstringpointerschar

解决方案


A char[]* in C# is technically not possible because managed types (in this case char[]) cannot be pointers, the more correct would be char**. This is a little confusing having a pointer to a pointer, but think of it as nothing more than an array of char arrays.

A pointer in unsafe C# code is simply a reference to a region of memory. In the C language, char arrays are generally null-terminated (byte value of 0) using continuous blocks of memory for the strings. The same applies in C#, the char* is simply a pointer to a continuous block of memory of char type.

Example:

Memory address 0x10000000 : h
Memory address 0x10000002 : e
Memory address 0x10000004 : l
Memory address 0x10000006 : l
Memory address 0x10000008 : o
Memory address 0x1000000A : \0

In C#, you could have char* ptr = (char*)0x10000000 - and the memory would point to the chars h, e, l, l, o, \0.

You can convert a single C# array to a char* using the fixed keyword, which pins the char array down, preventing garbage collection or memory movement.

char[] chars = new char[64];
// fill chars with whatever
fixed (char* charPtr = chars)
{
}

chars in the above example could also be a string.

Hope some of this info is useful.


推荐阅读