从字符串转换为 char* 只复制第一个字符

Converting from string to char* only copies the first character

我已经查看了大部分字符串到 char* 转换的 SO 答案,但它对我不起作用。这是我的代码:

public static void Main() {
    string name = "ELEM";
    unsafe{
          fixed(char* name_ptr = name) {
              Console.WriteLine(name_ptr->ToString());
          }
    }
} 
// Output: E

我需要这样做,因为我必须将 char* 传递到我的 C++ 自定义 DLL。为什么它只复制第一个字符,我怎样才能正确地将字符串转换为 char*?

你只得到第一个字符,因为 name_ptr 只是对单个字符的引用,当你调用 name_ptr->ToString() 时,你实际上调用了 char.ToString()

您应该使用 StringBuilder 来将字符串传递给 C/C++ DLL。参见 this question