c# - 在 C# String 构造函数 String(Char*) 中,为什么构造函数不期望指向字符数组的指针?
问题描述
我使用 C# 已经好几年了,但从未在 C# 中使用过指针。我正在使用 String API,但我不知道为什么 char* 实际上是一个数组而不是单个字符。
API定义:
[System.CLSCompliant(false)]
public String (char* value);
API 文档的片段:
参数
价值 Char*
指向以空字符结尾的 Unicode 字符数组的指针。
声明char* singleChar
是指向单个字符的指针吗?指针文档示例似乎是这样说的。
那么,为什么/如何它也可以是指向数组的指针?为什么不是参数类型char[]*
?
解决方案
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.
推荐阅读
- python - 根据条件和使用 Pyspark 的大数据计算时间差
- javascript - ScrollView 以编程方式滚动按钮按下反应本机
- reactjs - React Navigation 将用户数据传递给所有路线
- google-cloud-platform - 在任何一天没有将“n”个对象复制到云存储 (GCS) 时,在 Google Cloud 上配置警报
- c - 在 fork 循环中生成随机数
- vba - VBA 数据解析器更改文本值
- python - 为什么我需要“从 tqdm 导入 tqdm”而不仅仅是“导入 tqdm”?
- c# - 什么命名空间包含 HolograicFrameData 类型?
- error-handling - 为什么我不能使用 println!处理匹配语句中的错误但恐慌!作品?
- java - 我需要添加哪些附加条件/代码才能使“类列表插入代码”在 JUNIT 中变为绿色?