1

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • 1
    The same literal code file used in both projects? No. You could do it with a 3rd common project and a lot of `#ifdef..#endif` constructs though. – Blindy Jan 27 '15 at 06:30
  • i have the 'header' file of the service. Can you please explain what do you mean because i don't undersand. – Yanshof Jan 27 '15 at 06:45
  • 1
    You make a 3rd C++ project between the C# one and the C++ one. Your header file being in C++ means it has to be compiled in a C++ project (unmanaged for your original project and a managed stub with just the header to be referenced by the C# project). You need to make conditional compilation changes (`ref class` vs `class` etc), but the same header file *can* work for both. – Blindy Jan 27 '15 at 14:06

1 Answers1

6

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.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536