在合作开发时,C#时常需要调用C++DLL,当传递参数时时常遇到问题,尤其是传递和返回字符串是,现总结一下,分享给大家:
VC++中主要字符串类型为:LPSTR,LPCSTR, LPCTSTR, string, CString, LPCWSTR, LPWSTR等
但转为C#类型却不完全相同。
主要有如下几种转换:
将string转为IntPtr:IntPtr System.Runtime.InteropServices.Marshal.StringToCoTaskMemAuto(string)
将IntPtr转为string:string System.Runtime.InteropServices.MarshalPtrToStringAuto(IntPtr)
类型对照:
BSTR --------- StringBuilder
LPCTSTR --------- StringBuilder
LPCWSTR --------- IntPtr
handle---------IntPtr
hwnd-----------IntPtr
char *----------string
int * -----------ref int
int &-----------ref int
void *----------IntPtr
unsigned char *-----ref byte
Struct需要在C#里重新定义一个Struct
CallBack回调函数需要封装在一个委托里,delegate static extern int FunCallBack(string str);
注意在每个函数的前面加上public static extern +返回的数据类型,如果不加public ,函数默认为私有函数,调用就会出错。
在C#调用C++ DLL封装库时会出现两个问题:
Win32 Types
|
CLR Type
|
char, INT8, SBYTE, CHAR
|
System.SByte
|
short, short int, INT16, SHORT
|
System.Int16
|
int, long, long int, INT32, LONG32, BOOL , INT
|
System.Int32
|
__int64, INT64, LONGLONG
|
System.Int64
|
unsigned char, UINT8, UCHAR , BYTE
|
System.Byte
|
unsigned short, UINT16, USHORT, WORD, ATOM, WCHAR , __wchar_t
|
System.UInt16
|
unsigned, unsigned int, UINT32, ULONG32, DWORD32, ULONG, DWORD, UINT
|
System.UInt32
|
unsigned __int64, UINT64, DWORDLONG, ULONGLONG
|
System.UInt64
|
float, FLOAT
|
System.Single
|
double, long double, DOUBLE
|
System.Double
|