Marshaling Strings with P/Invoke

M

Markus Ewald

I've got a pretty simple function inside a C DLL that returns a pointer
to a unicode string:

extern "C" const wchar_t *__stdcall GetHelloWorld() {
return L"Hello World";
}

If I try to use it from .NETCF 2.0 application with the following
declaration, it fails (the same does seem to work flawlessly on .NET 2.0)

[DllImport("MyLibrary.Native.dll")]
[return: MarshalAs(UnmanagedType.LPWStr)]
private static extern string GetHelloWorld();

public static void Main() {
string hello = GetHelloWorld();
// hello = <The value of the local or argument 'hello' is
unobtainable at this time.>
}

But if I instead marshal the string by hand, it works:

[DllImport("MyLibrary.Native.dll")]
private static extern IntPtr GetHelloWorld();

public static void Main() {
string hello = Marshal.PtrToStringUni(GetHelloWorld());
// hello = "Hello World"
}

Of course I'd like to use the shorter, more elegant first option. Can
anyone think of a reason why I wouldn't work in a .NETCF 2.0 project?

-Markus-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top