C++ Class or Struct compatiblity with C struct

前端 未结 7 945
悲哀的现实
悲哀的现实 2020-12-10 07:36

Is it possible to write a C++ class or struct that is fully compatible with C struct. From compatibility I mean size of the object and memory locations of the variables. I k

7条回答
  •  感动是毒
    2020-12-10 08:16

    Yes.

    • Use the same types in the same order in both languages
    • Make sure the class doesn't have anything virtual in it (so you don't get a vtable pointer stuck on the front)
    • Depending on the compilers used you may need to adjust the structure packing (usually with pragmas) to ensure compatibility.

    (edit)

    • Also, you must take care to check the sizeof() the types with your compilers. For example, I've encountered a compiler that stored shorts as 32 bit values (when most will use 16). A more common case is that an int will usually be 32 bits on a 32-bit architecture and 64 bits on a 64-bit architecture.

提交回复
热议问题