Supernova009
Supernova009

Reputation: 95

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

Upvotes: 3

Views: 6014

Answers (3)

Supernova009
Supernova009

Reputation: 95

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

Upvotes: 1

William
William

Reputation: 772

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

Upvotes: 3

rkellerm
rkellerm

Reputation: 5512

Try to change the prototype line to:

private static extern int GetInstalledSoftwares(ref string pchInstalledSoftwares); 

(Send the string by reference).

Upvotes: 0

Related Questions