我需要从 C# 代码调用本机 DLL。由于我对 C/C++ 不是很熟悉,所以我不知道应该如何在 C# 中声明 C 中定义的结构,以便可以调用它。问题是两个参数似乎是一个结构数组,我不知道如何在 C# 中声明它(参见最后一个代码块):
c++头文件:
typedef enum
{
OK = 0,
//others
} RES
typedef struct
{
unsigned char* pData;
unsigned int length;
} Buffer;
RES SendReceive(uint32 deviceIndex
Buffer* pReq,
Buffer* pResp,
unsigned int* pReceivedLen,
unsigned int* pStatus);
c#声明:
enum
{
OK = 0,
//others
} RES
struct Buffer
{
public uint Length;
public ??? Data; // <-- I guess it's byte[]
}
[DllImport("somemodule.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern uint SendReceive(
uint hsmIndex,
uint originatorId,
ushort fmNumber,
??? pReq, // <-- should this be ref Buffer[] ?
uint reserved,
??? pResp, // <-- should this be ref Buffer[] ?
ref uint pReceivedLen,
ref uint pFmStatus);
在一个等效的 java 客户端中,我发现参数不仅仅是一个 Buffer,而是一个 Buffer 数组。在 C# 中,它看起来像这样:
var pReq = new Buffer[]
{
new Buffer { Data = new byte[] { 1, 0 }, Length = (uint)2 },
new Buffer {Data = requestStream.ToArray(), Length = (uint)requestStream.ToArray().Length },
//according to the header file, the last item must be {NULL, 0}
new Buffer { Data = null, Length = 0 }
};
var pResp = new Buffer[]
{
new Buffer { Data = new byte[0x1000], Length = 0x1000 },
//according to the header file, the last item must be {NULL, 0}
new Buffer { Data = null, Length = 0x0 }
};
这对我来说似乎很奇怪,因为 extern C 方法确实有一个指向 Buffer 结构 (Buffer*) 的指针,而不是指向 Buffer 数组 (Buffer[]*) 的指针。如何在 C# 中定义 Struct 和 extern 方法的参数类型?
任何帮助表示赞赏,谢谢。