To get a string from native code from managed code, the best way is to use a
StringBuilder
:
In native code:
extern "C" __declspec(dllexport) void FillString(char* myString, int length)
{
...
strcpy_s(myString, length, "hello");
}
In C# code:
[DllImport("YouNativeDLL")]
static extern void FillString(StringBuilder myString, int length);
public Test()
{
StringBuilder str = new StringBuilder(100);
FillString(str, str.Capacity);
string myString = str.ToString();
...
}
--------------------------------------
OK try using a callback and
Marshal
class then:
In native code:
typedef BOOL (__stdcall *MY_CALLBACK)(char* str, int length);
extern "C" __declspec(dllexport) void SetCallback(MY_CALLBACK callback)
{
char buffer[1000] = { 0 };
BOOL result = callback(buffer, 1000);
if (result)
MessageBox(NULL, "Callback returned true", buffer, MB_OK);
else
MessageBox(NULL, "Callback returned false", "", MB_OK);
}
In C# code:
delegate bool CALLBACK(IntPtr myString, int length);
[DllImport("Native")]
static extern void SetCallback(CALLBACK callback);
static bool Callback(IntPtr myString, int length)
{
string str = "hello";
if (str.Length + 1 > length)
return false;
IntPtr ptr = Marshal.StringToHGlobalAnsi(str);
byte[] bytes = new byte[str.Length + 1];
Marshal.Copy(ptr, bytes, 0, str.Length);
Marshal.Copy(bytes, 0, myString, bytes.Length);
Marshal.FreeHGlobal(ptr);
return true;
}
void SomeFunction()
{
SetCallback(Callback);
}