How to marshal type "Cstring" in .NET Compact Framework (C #)?
How to marshal type "Cstring" in .NET Compact Framework (C #)?
DLLname: Test_Cstring.dll (OS - WinCE 5.0), source code:
extern "C" __declspec(dllexport) int GetStringLen(CString str)
{
return str.GetLength();
}
I marshaled that into the .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 GetStringLen method in .NET CF was not successful! How to marshal this "Cstring" type? Any information on this would be much appreciated!
a source to share
You cannot marshal CString
as it is not a native type - this is a C ++ class that terminates an array char
.
You can marshal string
to char[]
because it char[]
is a native type. You need to have options for the features that you want to use P / Invoke, as the major types such as int
, bool
, char
or struct
, but not classes. More details here:
http://msdn.microsoft.com/en-us/library/aa446536.aspx
To call functions that take CString as an argument, you can do something like this:
//Compile with /UNICODE
extern "C" MFCINTEROP_API int GetStringLen(const TCHAR* str) {
CString s(str);
return s.GetLength();
//Or call some other function taking CString as an argument
//return CallOtherFunction(s);
}
[DllImport("YourDLL.dll", CharSet=CharSet.Unicode)]
public extern static int GetStringLen(string param);
In the above P / Invoke function, we are passing System.String
which can be bound to char*/wchar_t*
. The unmanaged function then creates an instance CString
and works with it.
It System.String
maps to by default char*
, so be careful what line the unmanaged version occupies. This version uses TCHAR
, which becomes wchar_t
when compiled with /UNICODE
. Therefore, you need to specify CharSet=CharSet.Unicode
in the attribute DllImport
.
a source to share