我需要编写一个包装类来使用其中一个C库的功能,我找到了这个解决方案,但是它有点奇怪,我觉得有一些简单的方法可以做到。以下是我找到的方法
extern "C" {
#include <some_dll_lib.h> //take all functions from lib
}
class Wrapper {
public:
//creating definition for each function, but with different names
Type* another_name_for_C_function_1();
Type* another_name_for_C_function_2();
//and so on...
};
Type* Wrapper::another_name_for_C_function1()
{
return real_name_C_function1_from_included_C_lib();//in function-definition use function from C-lib
}
Type* Wrapper::another_name_for_C_function2()
{
return real_name_C_function2_from_included_C_lib();
}如果这是做这种事的唯一方法,那就太可悲了。
发布于 2022-02-02 08:41:29
下面是一个将C数据结构和函数包装到C类中的最小示例:
foo.h
struct foo {
int a;
int b;
};
int bar(struct foo*);C(将进入C dll)
#include "foo.h"
int bar(struct foo* x) {
return x->a + x->b;
}包装。h:
extern "C" {
#include "foo.h"
}
class Wrapper {
foo x;
public:
Wrapper(int a, int b);
int bar();
};wrapper.cpp:
#include "wrapper.h"
Wrapper::Wrapper(int a, int b): x(foo{a, b}) {}
int Wrapper::bar() {
return ::bar(&x);
}main.cpp:
#include <iostream>
#include "wrapper.h"
int main() {
Wrapper w {1, 2};
std::cout << w.bar() << "\n";
return 0;
}https://stackoverflow.com/questions/70952013
复制相似问题