I am writing a C# library to be used by native C++ application. I am using C++/CLI as the Interoperability mechanisim.
I require to pass a callback function from C++
See the little-known UnmanagedFunctionPointer attribute, which is like DllImport for delegates, if you'd like to use CharSet
or whatnot.
GetDelegateForFunctionPointer
will work, but you need to add a [MarshalAs(UnmanagedType.LPWStr)]
attribute to the parameter in your delegate declaration in order for String
to get converted into wchar_t*
:
delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] string foo)
IntPtr func = ...;
MyDelegate del = (MyDelegate)Marshal.GetDelegateForFunctionPointer(func,
typeof(MyDelegate));
To pass a modifiable string, give a StringBuilder
. You need to explicitly reserve space for the unmanaged function to work with:
delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] StringBuilder foo)
StringBuilder sb = new StringBuilder(64); // reserve 64 characters.
del(sb);