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

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

Leave a Comment