用 extern "C"声明的函数将使用函数名作符号名,就像C函数一样。因此,只有非成员函数才能被声明为extern "C",并且不能被重载。尽管限制多多,extern "C"函数还是非常有用,因为它们可以象C函数一样被dlopen动态加载。冠以extern "C"限定符后,并不意味着函数中无法使用C++代码了,相反,它仍然是一个完全的C++函数,可以使用任何C++特性和各种类型的参数。
加载函数
在C++中,函数用dlsym加载,就像C中一样。不过,该函数要用extern "C"限定符声明以防止其符号名被mangle。
示例1.加载函数
代码:
//----------
//main.cpp:
//----------
#include <iostream>
#include <dlfcn.h>
int main() {
using std::cout;
using std::cerr;
cout << "C++ dlopen demo/n/n";
// open the library
cout << "Opening hello.so.../n";
void* handle = dlopen("./hello.so", RTLD_LAZY);
if (!handle) {
cerr << "Cannot open library: " << dlerror() << '/n';
return 1;
}
// load the symbol
cout << "Loading symbol hello.../n";
typedef void (*hello_t)();
// reset errors
dlerror();
hello_t hello = (hello_t) dlsym(handle, "hello");
const char *dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol 'hello': " << dlsym_error <<
'/n';
dlclose(handle);
return 1;
}
// use it to do the calculation
cout << "Calling hello.../n";
hello();
// close the library
cout << "Closing library.../n";
dlclose(handle);
}
//----------
// hello.cpp:
//----------
#include <iostream>
extern "C" void hello() {
std::cout << "hello" << '/n';
}
在hello.cpp中函数hello被定义为extern "C"。它在main.cpp中被dlsym调用。函数必须以extern "C"限定,否则我们无从知晓其符号名。
警告:
extern "C"的声明形式有两种:上面示例中使用的那种内联(inline)形式extern "C" , 还有才用花括号的extern "C" { ... }这种。 第一种内联形式声明包含两层意义:外部链接(extern linkage)和C语言链接(language linkage),而第二种仅影响语言链接。
下面两种声明形式等价:
代码:
extern "C" int foo;
extern "C" void bar();
和
代码:
extern "C" {
extern int foo;
extern void bar();
}
对于函数来说,extern和non-extern的函数声明没有区别,但对于变量就有不同了。如果您声明变量,请牢记:
代码:
extern "C" int foo;
和
代码:
extern "C" {
int foo;
}
是不同的物事(译者注:简言之,前者是个声明; 而后者不仅是声明,也可以是定义)。
加载类
加载类有点困难,因为我们需要类的一个实例,而不仅仅是一个函数指针。我们无法通过new来创建类的实例,因为类不是在可执行文件中定义的,况且(有时候)我们连它的名字都不知道。
解决方案是:利用多态性! 我们在可执行文件中定义一个带虚成员函数的接口基类,而在模块中定义派生实现类。通常来说,接口类是抽象的(如果一个类含有虚函数,那它就是抽象的)。
因为动态加载类往往用于实现插件,这意味着必须提供一个清晰定义的接口──我们将定义一个接口类和派生实现类。
接下来,在模块中,我们会定义两个附加的helper函数,就是众所周知的“类工厂函数(class factory functions)(译者注:或称对象工厂函数)”。其中一个函数创建一个类实例,并返回其指针; 另一个函数则用以销毁该指针。这两个函数都以extern "C"来限定修饰。
为了使用模块中的类,我们用dlsym像示例1中加载hello函数那样加载这两个函数,然后我们就可以随心所欲地创建和销毁实例了。
示例2.加载类
我们用一个一般性的多边形类作为接口,而继承它的三角形类(译者注:正三角形类)作为实现。
代码:
//----------
//main.cpp:
//----------
#include "polygon.hpp"
#include <iostream>
#include <dlfcn.h>
int main() {
using std::cout;
using std::cerr;
// load the triangle library
void* triangle = dlopen("./triangle.so", RTLD_LAZY);
if (!triangle) {
cerr << "Cannot load library: " << dlerror() << '/n';
return 1;
}
// reset errors
dlerror();
// load the symbols
create_t* create_triangle = (create_t*) dlsym(triangle, "create");
const char* dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol create: " << dlsym_error << '/n';
return 1;
}
destroy_t* destroy_triangle = (destroy_t*) dlsym(triangle, "destroy");
dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol destroy: " << dlsym_error << '/n';
return 1;
}
// create an instance of the class
polygon* poly = create_triangle();
// use the class
poly->set_side_length(7);
cout << "The area is: " << poly->area() << '/n';
// destroy the class
destroy_triangle(poly);
// unload the triangle library
dlclose(triangle);
}
//----------
//polygon.hpp:
//----------
#ifndef POLYGON_HPP
#define POLYGON_HPP
class polygon {
protected:
double side_length_;
public:
polygon()
: side_length_(0) {}
virtual ~polygon() {}
void set_side_length(double side_length) {
side_length_ = side_length;
}
virtual double area() const = 0;
};
// the types of the class factories
typedef polygon* create_t();
typedef void destroy_t(polygon*);
#endif
//----------
//triangle.cpp:
//----------
#include "polygon.hpp"
#include <cmath>
class triangle : public polygon {
public:
virtual double area() const {
return side_length_ * side_length_ * sqrt(3) / 2;
}
};
// the class factories
extern "C" polygon* create() {
return new triangle;
}
extern "C" void destroy(polygon* p) {
delete p;
}
加载类时有一些值得注意的地方:
◆ 你必须(译者注:在模块或者说共享库中)同时提供一个创造函数和一个销毁函数,且不能在执行文件内部使用delete来销毁实例,只能把实例指针传递给模块的销毁函数处理。这是因为C++里头,new操作符可以被重载;这容易导致new-delete的不匹配调用,造成莫名其妙的内存泄漏和段错误。这在用不同的标准库链接模块和可执行文件时也一样。
◆ 接口类的析构函数在任何情况下都必须是虚函数(virtual)。因为即使出错的可能极小,近乎杞人忧天了,但仍旧不值得去冒险,反正额外的开销微不足道。如果基类不需要析构函数,定义一个空的(但必须虚的)析构函数吧.