如何使用C / C ++结构中的C#代码? [英] How to use c/c++ struct in C# code?

查看:182
本文介绍了如何使用C / C ++结构中的C#代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一些服务,使用UDP给我字节数组。
该服务应用程序是在C语言开发 - 这此字节数组是一个C结构。

I'm using some service that send me byte array using UDP. This service application was developed in C - and this this byte array is a C struct.

我知道我可以重新定义在C#这个结构,并使用StructLayout属性有一个成员相同的对齐方式(是吗?)

I know that i can redefine this struct on C# and using the StructLayout attribute to have the same alignment of a member ( am i right ? )

但有可能使用托管C ++ / CLI定义相同的结构,并导入此托管C ++代码,以我的C#项目,并在这条路上做序列化?

But is it possible to define the same struct using managed C++/CLI and import this managed C++ code to my C# project and on this way to do the serialization ?

如果这是可能的 - 那么怎么办呢?
我找不到任何的例子,当我google一下。

If this is possible - so how to do it ? I can't find any example when i google it.

推荐答案

没有,这不会帮助你。 C ++ / CLI还区分本地结构(结构关键字)和一个管理结构(价值结构关键字)之间。你当然可以声明结构,使用#include最好,所以你会一直使用C的声明,你甚至可以迫使它的出口结构与的#pragma make_public 。但C#编译器将只看到一个不透明的值类型没有任何成员。

No, this will not help you. C++/CLI also distinguishes between a native struct (struct keyword) and a managed struct (value struct keyword). You can certainly declare the struct, using #include is best so you'll always use the C declaration, you can even force it to export the struct into the metadata with #pragma make_public. But the C# compiler will just see an opaque value type without any members.

在CLR使得大量的努力,使一个结构相同的本地布局的布局,一个C或C ++编译器将使用。重要的是要有效地互操作,这使得结构的 blittable 的。但它使用都相当不故意记载和事实上的规则依赖于特定类型的结构的成员和过程的位数的。在模糊的情况下,这将有利于[StructLayout(LayoutKind.Auto)来代替。你可以找到这样的事故的这里

The CLR makes plenty of effort to make the layout of a struct identical to the native layout that a C or C++ compiler will use. Important to make interop efficient, it makes the struct blittable. But the rules it uses are quite intentionally not documented and in fact depend on the specific types of the members of the struct and the bitness of the process. In obscure cases, it will favor [StructLayout(LayoutKind.Auto)] instead. You can find an example of such a mishap here.

有时不条款是搓,编译器不能假定约布局什么。您仍然可以使C ++ / CLI其用的#include来解析的C结构声明能力还清。这有助于避免事故的发生,无论是通过获取管理结构声明错误或当C代码的变化。你必须让你的C#代码中使用它来声明与公共价值结构关键字托管版本。值得怀疑,你会认为这是值得的额外项目的成本,它可能不是。

The "sometimes not" clause is the rub, a compiler cannot assume anything about layout. You can still make C++/CLI pay off by its ability to parse the C structure declaration with an #include. That helps avoid accidents, either by getting the managed structure declaration wrong or when the C code changes. You'll have to declare the managed version with public value struct keyword so your C# code use it. Doubtful you'll think it is worth the cost of an extra project, it probably isn't.

这篇关于如何使用C / C ++结构中的C#代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆