将字符指针从C#传递到c ++函数

问题描述:

我被困在c#实现方面,因为我是新的。事情是,我想传递一个指针(有内存)从c#代码,以便我的c + +应用程序可以复制pchListSoftwares缓冲区到pchInstalledSoftwares。

I am stuck in c# implementation side, as I am pretty new to it. The thing is, I want to pass a 'pointer'(having memory) from c# code so that My c++ application can copy pchListSoftwares buffer to pchInstalledSoftwares. I am not able to figure out how to pass pointer from c# side.

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

native c++ code(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 );

}

传递简单的'string'不起作用...

Passing simple 'string' is not working...

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

非常感谢任何帮助...

Any kind of help is greatly appreciated...

尝试使用StringBuilder

Try using a 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());
}