Pass a function pointer from C ++, which is called by C #. Function arguments include wide char string (LPCWSTR)

I am writing a C # library that will be used by a C ++ application. I use C ++ / CLI as an interaction mechanic.

I need to pass a callback function from C ++ to C # (using C ++ / CLI as an intermediate level). The C # library should call a C ++ function with a null-terminated string with wide characters; i.e. the prototype of the callback function is

Func (LPCWSTR pszString);

There are other parameters, but they are not essential for this discussion.

I searched the net and found Marshal.GetDelegateForFunctionPointer. The method I can use. The problem is that it converts System.String from C # to char * and not the wchar_t * I'm looking for.

Also, what is the best method to get this sample code, including the C ++ / CLI part, if possible. C ++ / CLI dll depends on C # dll. The method must be called synchronously.

+3
source share
2 answers

GetDelegateForFunctionPointerwill work, but you need to add an attribute [MarshalAs(UnmanagedType.LPWStr)]to the parameter in the delegate declaration in order to Stringconvert to wchar_t*:

delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] string foo)

IntPtr func = ...;
MyDelegate del = (MyDelegate)Marshal.GetDelegateForFunctionPointer(func,
                                 typeof(MyDelegate));

To pass a mutable string, give StringBuilder. You need to explicitly reserve space for an unmanaged function to work with:

delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] StringBuilder foo)

StringBuilder sb = new StringBuilder(64); // reserve 64 characters.

del(sb);
+7
source

See a little-known UnmanagedFunctionPointerattribute that is similar to DllImportfor delegates if you want to use CharSetor something else.

+2
source

All Articles