CLR:将(C#)字符串转换为以null结尾的char(C)数组?

时间:2013-06-09 07:43:22

标签: c# string type-conversion clr

我已经创建了一个CLR项目,现在我需要将C#textBox.Text属性转换为C-ansi字符数组(以null结尾)。我需要将文本传递给C函数,如下所示:

UPDATE2:

// Form1.h (C#)
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

myCFunction(textBoxName.Text); // wrong

}

// utils.h (C) - inside the same project as Form1.h
void myCFunction(char* szName);

// utils.cpp (C) - inside the same project as Form1.h
void myCFunction(char* szName)
{
  // do something
}

2 个答案:

答案 0 :(得分:1)

如果你使用P / Invoke将它传递给C函数,我相信marshaller会根据应用于声明中参数的属性为你做这件事。

所以基于this documentation,你可能想要这样的东西:

[DllImport("YourLibrary.Dll")]
public extern void Foo([UnmanagedType.LPStr] string text)

答案 1 :(得分:0)

char* str2 = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(textBox1->Text);

简单。