C++ 和 C# 类型转换
using System.Runtime.InteropServices;
C++ | C# | 备注 |
---|---|---|
HANDLE (void*) | System.IntPtr | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void MethodCallBack(int param1, int param2); |
BYTE (unsigned char) | System.Byte | |
SHORT (short) | System.Int16 | |
WORD (unsigned short) | System.UInt16 | |
INT (int) | System.Int16 | Int32 |
UINT (unsigned int) | System.Int16 | Int32 |
LONG (long) | System.Int32 | |
ULONG (unsigned long) | System.UINT32 | |
DWORD (unsigned long) | System.UINT32 | |
DECIMAL | System.Decimal | |
BOOL (long) | System.Boolean | |
CHAR (char) | System.Char | |
LPSTR (char*) LPWSTR (wchar_t*) LPCSTR (const char*) LPCWSTR (const wchar_t*) PCHAR (char*) BSTR |
System.String | 不修改字符串内容,只传参的,用string 需要修改并传出使用的,用StringBuilder+MarshalAs/ DllImport.CharSet=Unicode |
unsigned char* | [MarshalAs(UnmanagedType.LPArray)] byte[] |
string, StringBuilder, [MarshalAs(UnmanagedType.LPArray)] IntPtr, |
FLOAT (float) | System.Single | |
DOUBLE (double) | System.Double | |
VARINT | System.Object | |
PBYTE (byte*) | System.Byte[] | |
更复杂的C++转C#,可以使用 P/Invoke Interop Assistant
C#调用C++
int Method(unsigned char* data, float param1, float& param2);
[DllImport("XXXLib.dll")]
public static extern int Method([MarshalAs(UnmanagedType.LPArray)] byte[] data, float parm1, out float param2);
回调函数
typedef void(*FuncCallback)(int id, bool bComplete);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void FuncCallback(int param1, bool param2);