Passing char pointer from C# to c++ function

c#, c++, managed, unmanaged

Solution

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

Problem

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

Original source