ABI边界的可移植性

       在二进制接口边界应该使用足够可移植的类型和惯用法。可移植类型指C的内置类型或只含有C内置类型的结构体(struct)。Class类型只有在调用方和被调用方在内存布局和调用约定一致的情况下才可以使用,这通常只有在双方使用同样的编译器和编译选项的情况下才成为可能。

如何使一个class转化为可移植的C等价物

       当调用方可能被另一种编译器或语言编译的时候,使用一定的调用惯例将class"flatten"到“extern C”接口。

示例:
// class widget {
//   widget();
//   ~widget();
//   double method(int, gadget&);
// };
extern "C" { // functions using explicit "this"
  struct widget; // + opaque type (fwd decl only)
  widget* STDCALL widget_create(); // ctor → create new "this"
  void STDCALL widget_destroy(widget*); // dtor → consume "this"
  double STDCALL widget_method(widget*, int, gadget*); // method → use "this"
}
       这个转化实际上相当于将class定义的数据和接口分离为C struct和对应的一组接口,显示使用class的this指针


原文:http://technet.microsoft.com/en-us/magazine/hh438475.aspx

Portability At ABI Boundaries (Modern C++)

Use sufficiently portable types and conventions at binary interface boundaries. A “portable type” is a C built-in type or a struct that contains only C built-in types. Class types can only be used when caller and callee agree on layout, calling convention, etc. This is only possible when both are compiled with the same compiler and compiler settings.

How to flatten a class for C portability

When callers may be compiled with another compiler/language, then “flatten” to an “extern C” API with a specific calling convention:

Visual C++

// class widget {
//   widget();
//   ~widget();
//   double method(int, gadget&);
// };
extern "C" { // functions using explicit "this"
  struct widget; // + opaque type (fwd decl only)
  widget* STDCALL widget_create(); // ctor → create new "this"
  void STDCALL widget_destroy(widget*); // dtor → consume "this"
  double STDCALL widget_method(widget*, int, gadget*); // method → use "this"
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值