简体   繁体   中英

Passing char pointer from C# to c++ function

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.

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

}

Passing simple 'string' is not working...

C# implementation

[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...

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

My mistake... remove 0 in call to GetInstalledSoftwares(0, b); .

Try to change the prototype line to:

private static extern int GetInstalledSoftwares(ref string pchInstalledSoftwares); 

(Send the string by reference).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM