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

3

我在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());
}

非常感谢您提供的任何帮助...

3个回答

3

尝试使用 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());
}

1

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


0

尝试将原型行更改为:

private static extern int GetInstalledSoftwares(ref string pchInstalledSoftwares); 

通过引用发送字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接