How to use c/c++ struct in C# code?

白昼怎懂夜的黑 提交于 2019-12-08 04:23:41

问题


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.

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 ? )

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 ?

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


回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/28164450/how-to-use-c-c-struct-in-c-sharp-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!