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"
}




 

 

posted @ 2013-06-16 12:50  爱生活,爱编程  阅读(264)  评论(0编辑  收藏  举报