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).
精彩评论