将C++成员函数传递给 C 函数
Pass a C++ member function to a C function
我们有一个接受C函数指针的结构:
int one(int x)
{
}
int two(int x)
{
}
struct Cstruct
{
int (*fn1)(int);
int (*fn2)(int);
};
现在我有一个C++类,它有以下方法:
class A
{
public:
int one(int x)
{
}
int two(int x)
{
}
int three(int x)
{
struct Cstruct cstr = {&this->one, &this->two};
}
};
尝试将类 A 方法地址初始化为 Cstruct 编译器实例时,是否给出了无效转换的错误?
如何将类成员函数地址分配给 Cstruct?
您无法执行此操作,因为指向非静态成员函数C++指针与非成员函数指针类型不兼容。这是因为成员函数需要一个额外的参数 - 需要调用成员函数的对象,它成为调用this
指针。
如果将成员函数设置为静态,则代码将编译。但是,它不一定能实现您想要实现的目标,因为one
和two
无法访问A
的其他非静态成员。
将成员函数传递给 C 函数的一个技巧需要传递一个带有"注册"记录的附加void*
指针,并让 C 代码将其传递回静态回调函数:
struct Cstruct
{
void *context; // Add this field
int (*fn1)(void*, int);
int (*fn2)(void*, int);
};
class A
{
public:
static int oneWrap(void* ptr, int x)
{
return static_cast<A*>(ptr)->one(x);
}
static int twoWrap(void* ptr, int x)
{
return static_cast<A*>(ptr)->two(x);
}
int one(int x)
{
}
int two(int x)
{
}
int three(int x)
{
struct Cstruct cstr = {this, &this->oneWrap, &this->twoWrap};
}
};
C 代码需要将context
的值传递给fn1
并fn2
:
cs.fn1(cs.context, 123);
cs.fn2(cs.context, 456);
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针