将char指针从C#传递给c ++函数

我被困在c#实现方面,因为我对它很陌生。 问题是,我想从c#代码传递一个’指针’(有内存),这样我的c ++应用程序就可以将pchListSoftwares缓冲区复制到pchInstalledSoftwares。 我无法弄清楚如何从c#侧传递指针。

本机c ++代码(MyNativeC ++ DLL.dll)

void GetInstalledSoftwares(char* pchInstalledSoftwares){ char* pchListSoftwares = NULL; ..... ..... pchListSoftwares = (char*) malloc(255); /* code to fill pchListSoftwares buffer*/ memcpy(pchInstalledSoftwares, pchListSoftwares, 255); free(pchListSoftwares ); } 

传递简单的’字符串’不起作用……

C#实现

 [DllImport("MyNativeC++DLL.dll")] private static extern int GetInstalledSoftwares(string pchInstalledSoftwares); static void Main(string[] args) { ......... ......... string b = ""; GetInstalledSoftwares(0, b); MessageBox.Show(b.ToString()); } 

非常感谢任何forms的帮助……

尝试使用StringBuilder

 [DllImport("MyNativeC++DLL.dll")] private static extern int GetInstalledSoftwares(StringBuilder pchInstalledSoftwares); static void Main(string[] args) { ......... ......... StringBuilder b = new StringBuilder(255); GetInstalledSoftwares(0, b); MessageBox.Show(b.ToString()); } 

我的错误…在调用GetInstalledSoftwares(0, b);删除0 GetInstalledSoftwares(0, b);

尝试将原型行更改为:

 private static extern int GetInstalledSoftwares(ref string pchInstalledSoftwares); 

(通过引用发送字符串)。