是否有可能继承C结构的C ++和使用指针在C code中的结构? [英] Is it possible to subclass a C struct in C++ and use pointers to the struct in C code?

查看:123
本文介绍了是否有可能继承C结构的C ++和使用指针在C code中的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有这样做的副作用:

Is there a side effect in doing this:

C code:

struct foo {
      int k;
};

int ret_foo(const struct foo* f){ 
    return f.k; 
}

C ++ code:

C++ code:

class bar : public foo {

   int my_bar() { 
       return ret_foo( (foo)this ); 
   }

};

这里有一个的externC围绕C ++ code和每code是它自己的编译单元内。

There's an extern "C" around the C++ code and each code is inside its own compilation unit.

这是可跨编译器?

推荐答案

这是完全合法的。在C ++中类和结构是相同的概念,与所有的结构成员默认都是公有的除外。这是唯一的区别。所以,询问是否可以延长一个结构并不比询问是否可以扩展一个类不同的。

This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.

这里有一点需要注意。还有的由编译器来编译布局的一致性无法保证的。所以,如果你用不同的编译器比你的C ++ code编译C code,你可能会碰到有关成员布局(填充尤其是)的问题。这可以使用来自同一供应商的C和C ++编译器时发生,甚至

There is one caveat here. There is no guarantee of layout consistency from compiler to compiler. So if you compile your C code with a different compiler than your C++ code, you may run into problems related to member layout (padding especially). This can even occur when using C and C++ compilers from the same vendor.

我的有无的过这种情况用gcc和g ++。我曾在其使用的几个大结构的项目。不幸的是,G ++挤满了结构比GCC,造成显著的问题分享C和C ++ code的对象显著宽松。我们最终不得不手动设置包装插入填充,使C和C ++ code对待结构相同。但是请注意,不管子类的可能会出现这个问题。事实上,我们并没有在这种情况下继承了C结构。

I have had this happen with gcc and g++. I worked on a project which used several large structs. Unfortunately, g++ packed the structs significantly looser than gcc, which caused significant problems sharing objects between C and C++ code. We eventually had to manually set packing and insert padding to make the C and C++ code treat the structs the same. Note however, that this problem can occur regardless of subclassing. In fact we weren't subclassing the C struct in this case.

这篇关于是否有可能继承C结构的C ++和使用指针在C code中的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆