How to pass strings from C# to C++ (and from C++ to C#) using DLLImport?

Jsncrdnl picture Jsncrdnl · May 29, 2012 · Viewed 32k times · Source

I've been trying to send a string to/from C# to/from C++ for a long time but didn't manage to get it working yet ...

So my question is simple :
Does anyone know some way to send a string from C# to C++ and from C++ to C# ?
(Some sample code would be helpful)

Answer

sithereal picture sithereal · May 29, 2012

in your c code:

extern "C" __declspec(dllexport)
int GetString(char* str)
{
}

extern "C" __declspec(dllexport)
int SetString(const char* str)
{
}

at .net side:

using System.Runtime.InteropServices;


[DllImport("YourLib.dll")]
static extern int SetString(string someStr);

[DllImport("YourLib.dll")]
static extern int GetString(StringBuilder rntStr);

usage:

SetString("hello");
StringBuilder rntStr = new StringBuilder();
GetString(rntStr);