How to marshal the type of “Cstring” in .NET Compact Framework(C#)?
DLLname:Test_Cstring.dll(OS is WinCE 5.0),source code:
extern "C" __declspec(dllexport) int GetStringLen(CString str)
{
return str.GetLength();
}
I marshal that in .NET Compact Framework(C#),for example:
[DllImport("Test_Cstring.dll", EntryPoint = "GetStringLen", SetLastError = true)]
public extern static int GetStringLen(string s);
private void Test_Cstring()
{
int len=-1;
len=GetStringLen("abcd");
MessageBox.Show("Length:"+len.ToString()); //result is -1,so PInvoke is unsuccessful!
}
The Method of “GetStringLen” in .NET CF is unsuccessful!
How to marshal this type of “Cstring”?
Any information about it would be very appreciated!
You can’t marshal
CStringas it’s not a native type – it’s a C++ class that wraps up achararray.You can marshal
stringtochar[]aschar[]is a native type. You need to have the parameters to the function you want to P/Invoke into as basic types likeint,bool,charorstruct, but not classes. Read more here:http://msdn.microsoft.com/en-us/library/aa446536.aspx
In order to call functions that take CString as an argument you can do something like this:
In the above P/Invoke function we pass in a
System.Stringwhich can marshal tochar*/wchar_t*. The unmanaged function then creates a instance ofCStringand works with that.By default
System.Stringis marshalled tochar*, so be careful with what kind of string the unmanaged version takes. This version usesTCHAR, which becomeswchar_twhen compiled with/UNICODE. That’s why you need to specifyCharSet=CharSet.Unicodein theDllImportattribute.