C++ Class or Struct compatiblity with C struct

前端 未结 7 947
悲哀的现实
悲哀的现实 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:20

    C and C++ are different languages but it has always been the C++'s intention that you can have an implementation that supports both languages in a binary compatible fashion. Because they are different languages it is always a compiler implementation detail whether this is actually supported. Typically vendors who supply both a C and C++ compiler (or a single compiler with two modes) do support full compatibility for passing POD-structs (and pointers to POD-structs) between C++ code and C code.

    Often, merely having a user-defined constructor breaks the guarantee although sometimes you can pass a pointer to such an object to a C function expecting a pointer to a struct with and identical data structure and it will work.

    In short: check your compiler documentation.

提交回复
热议问题