c语言 dlsym 用法,使用dlopen和dlsym来使用C++中的类

c语言 dlsym 用法,使用dlopen和dlsym来使用C++中的类includeintma usingstd cout usingstd cerr loadthetrian triangle dlopen triangle so RTLD LAZY if triangle cerr lt lt Cannotloadli lt

#include 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 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;

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224997.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 上午10:22
下一篇 2026年3月17日 上午10:22


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号