【发布时间】:2020-10-31 17:48:33
【问题描述】:
我用 C 语言编写了一个 dll,它具有在 C# 中引用 DLL 时可以调用的函数。如果我使用像 int 这样的基本类型,它可以正常工作,但是由于语言差异,C# 中的结构与 C 中的结构略有不同。这是一个例子。这是 C# 中的函数定义:
[DllImport("hello_world_cuda.dll", CharSet = CharSet.Auto)]
public static extern Batch Cut();
这是在 C 中的:
extern "C" Batch __declspec(dllexport) __stdcall Cut()
你可以看到返回类型Batch是一样的,但是这里是它在C#中的定义
class Envelope
{
public byte[] Payload;
public byte[] Signature;
}
class Batch
{
public Envelope[] Messages;
public int MsgCount;
}
这是C中的定义
struct Envelope
{
public:
char* Payload;
char* Signature;
};
struct Batch
{
public:
Envelope* Messages;
int MsgCount;
};
如何克服这些语言差异,以便在 C# 中成功调用 DLL?
【问题讨论】:
-
c 中的字符数组以 '\0' 结束。因此,在 c# 中,如果您使用的是 byte[],请确保将 '\0' 添加为最后一个 byte[]。
-
DLL如何分配内存?谁负责解除分配。这是您需要解决的第一件事。