Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] Unicode callbacks

Started by Headkaze Jul 17, 2008 at 5:32 PM 3 replies 1k views
Original Post
Headkaze
Headkaze
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.
benryves
benryves
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 +++]
Headkaze
Headkaze
Yes it did, thanks! :)
Anon Mike
Anon Mike
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
Headkaze
Headkaze
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.