3. 解决方案

3.1. extern "C"

C++ 有一个特殊的关键字来声明具有 C 绑定的函数extern "C"。 声明为extern "C"的函数使用函数名作为符号名,就像 C 函数一样。 因此,只有非成员函数可以声明为extern "C",并且它们不能被重载。

尽管存在严重的局限性,extern "C"函数非常有用,因为它们可以使用dlopen像 C 函数一样动态加载。

这并意味着限定为extern "C"的函数不能包含 C++ 代码。 这样的函数是一个功能齐全的 C++ 函数,可以使用 C++ 功能并接受任何类型的参数。

3.2. 加载函数

在 C++ 中,函数加载方式与 C 中相同,使用dlsym。 你想要加载的函数必须限定为extern "C"以避免符号名称被破坏(mangled)。

示例 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定义在hello.cppextern "C";它在main.cpp中使用dlsym调用加载。 该函数必须限定为extern "C",否则我们无法知道它的符号名称。

Warning

有两种不同形式的extern "C"声明extern "C"如上所述,以及extern "C" { … }大括号之间的声明。 第一种(内联)形式是具有外部链接和 C 语言链接的声明;第二种形式仅影响语言链接。 因此,以下两个声明是等效的

extern "C" int foo;
extern "C" void bar();
            

extern "C" {
     extern int foo;
     extern void bar();
}

由于extern和非extern 函数声明之间没有区别,只要你不声明任何变量,这就没有问题。 如果你声明变量,请记住

extern "C" int foo;

extern "C" {
    int foo;
}

同的。

有关进一步的澄清,请参阅 [ISO14882],7.5,特别注意第 7 段,或 [STR2000],第 9.2.4 段。

在对外部变量进行花哨的操作之前,请仔细阅读另请参阅部分中列出的文档。

3.3. 加载类

加载类有点困难,因为我们需要一个类的实例,而不仅仅是指向函数的指针。

我们不能使用new来创建类的实例,因为该类未在可执行文件中定义,并且(在某些情况下)我们甚至不知道它的名称。

解决方案是通过多态性实现的。 我们在可执行文件中定义一个基类,接口类,其中包含虚成员,并在模块中定义一个派生类,实现类。 通常,接口类是抽象的(如果一个类具有纯虚函数,则该类是抽象的)。

由于类的动态加载通常用于插件——插件必须公开明确定义的接口——无论如何我们都必须定义一个接口和派生的实现类。

接下来,仍在模块中,我们定义了两个额外的辅助函数,称为类工厂函数。 其中一个函数创建类的实例并返回指向它的指针。 另一个函数接受指向工厂创建的类的指针并销毁它。 这两个函数都限定为extern "C".

要使用模块中的类,请使用dlsym就像我们加载 hello 函数一样加载两个工厂函数;然后,我们可以根据需要创建和销毁任意数量的实例。

示例 2. 加载类

在这里,我们使用通用的polygon类作为接口,并将派生类triangle作为实现。

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

加载类时,需要注意一些事项