简体   繁体   English

从 C# 调用 C dll,返回类型略有不同

[英]Calling C dll from C#, return types slightly different

I've written a dll in C which has functions I can call when referencing the DLL in C#.我在 C 中写了一个 dll,它具有我可以在引用 ZD7EFADB19FBE7D39724FDZD7EFADB19FBE7D39724FD5 中的 DLL 时调用的函数If I use a basic type like an int it works fine, but I have structs which are slightly different in C# than they are in C due to language differences.如果我使用像 int 这样的基本类型,它可以正常工作,但是由于语言差异,我在 C# 中的结构与在 C 中的结构略有不同。 Here is an example.这是一个例子。 This is the function definition in C#:这是 C# 中的 function 定义:

[DllImport("hello_world_cuda.dll", CharSet = CharSet.Auto)]
public static extern Batch Cut();

And here is it in C:这是 C 中的内容:

extern "C" Batch __declspec(dllexport) __stdcall Cut()

You can see the return type Batch is the same, but here is its definition in C#可以看到返回类型 Batch 是一样的,但是这里是它在 C# 中的定义

class Envelope
{
    public byte[] Payload;
    public byte[] Signature;
}

class Batch
{
    public Envelope[] Messages;
    public int MsgCount;
}

And here is the definition in C这是 C 中的定义

struct Envelope
{
public:
    char* Payload;
    char* Signature;
};

struct Batch
{
public:
    Envelope* Messages;
    int MsgCount;
};

How do I overcome these language differences in order to successfully make the DLL call in C#?如何克服这些语言差异,以便在 C# 中成功调用 DLL?

You should define Envelope and Batch as structs in C# too, and apply the StructLaylout attribute:您也应该在 C# 中将EnvelopeBatch定义为结构,并应用StructLaylout属性:

eg:例如:

[StructLayout(LayoutKind.Sequential, Pack=0)]
struct Envelope
{
   ...
}

Pointers in an unmanaged language do not map to managed arrays as you have done, this is why it is complaining.非托管语言中的指针不会像您所做的那样 map 指向托管 arrays,这就是它抱怨的原因。 char is (almost always, with very limited exceptions) an 8 bit value that maps well to byte in C# as you've noticed, but you need to make them pointers in the managed struct as well:正如您所注意到的, char是(几乎总是,除了非常有限的例外)一个 8 位值,它很好地映射到 C# 中的byte ,但是您还需要在托管结构中使它们成为指针:

unsafe struct Envelope
{
    public byte* Payload;
    public byte* Signature;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM