通过C++类方法地址调用类的虚方法

来源:互联网 发布:网页怎么看淘宝直播间 编辑:程序博客网 时间:2024/05/22 09:40

    1. 类的定义,编译成动态链接库。

Canvas.h

#ifndef CANVAS_H#define CANVAS_Hclass Canvas{public:    Canvas();    virtual ~Canvas();    virtual void draw();    virtual void round(int angle);        void view();private:    int m_value;};#endif

Canvas.cpp

#include "Canvas.h"#include <iostream>using namespace std;Canvas::Canvas()    : m_value(100){}Canvas::~Canvas(){}void Canvas::draw(){    cout<<"virutal Canvas::draw"<<endl;}void Canvas::round(int angle){    m_value += angle;    cout<<"virtual Canvas::round m_value="<<m_value<<endl;}void Canvas::view(){    cout<<"Canvas::view"<<endl;}

编译成动态链接库的命令是:

g++ -fPIC -g -c Canvas.cpp
g++ -g -shared -Wl,-soname,libCanvas.so.1 -o libCanvas.so.1.0.1 Canvas.o -lstdc++


2. 用nm命令查看动态链接库的导出函数:

nm libCanvas.so.1.0.1

查看到Canvas::round导出的符号是:“_ZN6Canvas5roundEi”。


3. 那么可以像如下文件一样调用:

#include <iostream>#include <dlfcn.h>#include "canvas/Canvas.h"using namespace std;//typedef void (*canvas_round_func)(int);typedef void (*canvas_round_func)(Canvas* self, int);   // 定义Canvas::round对应的函数指针。第一个参数指向类实例。int main(){    void* lib = dlopen("libCanvas.so", RTLD_LAZY);    Canvas canvas;    canvas.draw();//    canvas.round(0);    canvas.view();    canvas_round_func func = (canvas_round_func)dlsym(lib, "_ZN6Canvas5roundEi");    if (func)    {           cout<<"get function ok."<<endl;         func(&canvas, 10);    }       else    {           cout<<"return null"<<endl;    }       dlclose(lib);    return 0;}
编译:

g++ -g -c main.cpp -o main.o
echo Compile ... Done.
g++ -g -o main.exe main.o -L. -lCanvas -ldl
echo Linking ... Done.

结果是可以正常运行的。

原创粉丝点击