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

旧时模样 提交于 2019-12-06 19:33:26
Hans Passant

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.

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