misak
misak

Reputation: 342

Marshaling callback to native dll

I am working with callback going from unmanged native library to my managed C# code. Callback function is declared in header file:

typedef void* (TNotice)(wchar_t *msg, bool error);

Callback has string parameter msg.I don't khow, why doesn't work declaration in c#:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr CallbackDelegate([MarshalAs(UnmanagedType.LPWStr)]string msg, bool error);

but declaration:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr CallbackDelegate([MarshalAs(UnmanagedType.LPWStr)]StringBuilder msg, bool error);

works fine.

Upvotes: 2

Views: 197

Answers (1)

John Willemse
John Willemse

Reputation: 6698

You have to use a StringBuilder, because the parameter is an out parameter or return value. In those cases you cannot use a regular string. The marshalling you use is correct.

Upvotes: 5

Related Questions