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("XXX.dll", CallingConvention = CallingConvention.Cdecl)], 特殊情况还需要加 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[] | |
| SIZE_T | System.UINT64 | |


更复杂的C++转C#,可以使用 P/Invoke Interop Assistant 或者 查看p-invoke.net
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);
// 声明
private static FuncCallback _callbak = new FuncCallback(CallBackMethod);
// 实现
public static void CallBackMethod(int param1, int param2)
{
// TODO
}

浙公网安备 33010602011771号