[.net] Unicode callbacks

Started by
3 comments, last by Headkaze 15 years, 9 months ago
I can't seem to find any information on forcing a callback from a C++ dll to C# to use Unicode strings. I use a StringBuilder type for the function prototype but it doesn't seem to know it's a PWCHAR that is being returned. Is there any way to explicity tell it to expect a Unicode string? Here is the callback type in C++
typedef int (__stdcall *WMP_ERROR)(long ErrorCode, PWCHAR ErrorDesc);
and here it is defined in C#
public delegate void WMP_ERROR(uint ErrorCode, StringBuilder ErrorDesc);

[MarshalAs(UnmanagedType.FunctionPtr)]
WMP_ERROR pError = null;
When I output ErrorDesc.ToString() it will only print the first letter of the string (as it would if it expects an Ansi string.
Advertisement
You could try this:
public delegate void WMP_ERROR(	uint ErrorCode,	[MarshalAs(UnmanagedType.LPWStr)] StringBuilder ErrorDesc);
Hope that fixes it!

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

Yes it did, thanks! :)
Could this be happening because you aren't using PWSTR (or LPWSTR)? PWCHAR is technically a pointer to a single character, not a string.
-Mike
The actual issue with it displaying one letter is not because I was using PWCHAR because at the end of the day all I'm passing from the C++ dll to C# is a pointer value which changes from PWCHAR to LPWSTR when it's marshalled back to C#.

The problem was because C# defaults to an ANSI string pointer when using StringBuilder and a callback so when you try to output the string it outputs one letter because the second byte of the UNICODE string was NULL terminating the ANSI string. I believe UNICODE strings use two NULL's for the terminator.

This topic is closed to new replies.

Advertisement