Using DLLImport with a function requiring char *

  • Thread starter Thread starter Jason Bell
  • Start date Start date
J

Jason Bell

I'm an experienced programmer, but a newbie to c#, so please be kind :)

In a c++, unmanaged, DLL of my own making I have a function called

void XGL_Core_SetCaption(XGL_Core * core, char * caption);

Using DLLImport I've gotten all functions working except for the ones
requiring char * . Anyone care to inform me how to pass the contents of a
c# string to this c++ function? I've tried passing string and char[], with
no luck.

Any thoughts?
 
How did you declare your PInvoke signature?
If you modify the string pointed to by char*, you have to pass a
StringBuilder with sufficient size to hold the new string + terminating
null.
Else you can pass a System.String.
Note that you need to help the interop marshaler a bit when your native code
is a UNICODE build, by applying the MarshalAs(UnmanagedType.LPWStr)]
attribute to the argument.
(...., [In,Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder s)
else the interop marshaler converts wide-char strings to multi-byte by
default.
(...., [In,Out]StringBuilder s)

Willy.
 
Thanks, I got it working by marshaling it as LPStr. LPWStr just passed the
first character in the string. Here's what I used:

[DllImport("XGL.dll", EntryPoint="XGL_Core_SetCaption",

ExactSpelling=false,CallingConvention=CallingConvention.Cdecl)]
public unsafe static extern void SetCaption( void * Core,
[MarshalAs(UnmanagedType.LPStr)]string s );

Thanks again.
 
Jason,
Well, actualy all characters are passed (as unicode characters), it's just
the native code that looks for a single null (0x00) byte in the input buffer
as string terminator.
Note that there is no need to specify LPStr as it's the default.

Willy.
 
heh that's bizarre, I tried just passing a string without marshalling
originally, and it didn't work. Now it seems to. Ah well, I must have
overlooked something at point.

Thanks again for your help.
 
There is always marshaling involved when transitioning from managed to
unmanaged.
The point is that if you don't specify the attribute, by default the
marshaler converts Unicode to MBSC and vice-versa.

Willy.
 
Back
Top