3

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

Supernova009
  • 95
  • 1
  • 7

3 Answers3

3

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());
}
William
  • 772
  • 7
  • 18
1

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

bluish
  • 26,356
  • 27
  • 122
  • 180
Supernova009
  • 95
  • 1
  • 7
0

Try to change the prototype line to:

private static extern int GetInstalledSoftwares(ref string pchInstalledSoftwares); 

(Send the string by reference).

rkellerm
  • 5,362
  • 8
  • 58
  • 95