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

2019-06-02 08:37发布

问题:

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.



标签: c# c++-cli