将C ++成员函数传递给C函数 [英] Pass a C++ member function to a C function
问题描述
我们有一个接受C函数指针的结构:
We have a structure that accepts C function pointers:
int one(int x)
{
}
int two(int x)
{
}
struct Cstruct
{
int (*fn1)(int);
int (*fn2)(int);
};
现在我有一个具有以下方法的C ++类:
Now I have a C++ class that has below methods:
class A
{
public:
int one(int x)
{
}
int two(int x)
{
}
int three(int x)
{
struct Cstruct cstr = {&this->one, &this->two};
}
};
在尝试将类A方法的地址初始化为Cstruct编译器的实例时,却给出了无效转换的错误?
While trying to initialize class A methods address to a instance of Cstruct compiler is giving error of an invalid conversion?
如何为Cstruct分配Class成员函数地址?
How can I assign the Class member function address to Cstruct?
推荐答案
您不能这样做,因为指向非静态成员函数的C ++指针与非成员函数指针类型不兼容.这是因为成员函数需要一个附加参数-需要在其上调用成员函数的对象,该对象成为调用内的 this
指针.
You cannot do it, because C++ pointer to a non-static member function is not compatible with a non-member function pointer type. This is because member functions require an additional argument - the object on which the member function needs to be called, which becomes this
pointer inside the invocation.
如果将成员函数设为静态,则代码将被编译.但是,它不一定能达到您想要的目的,因为 one
和 two
无法访问 A
的其他非静态成员.
If you make your member functions static, your code would compile. However, it would not necessarily do what you want to achieve, because one
and two
have no access to other non-static members of A
.
将成员函数传递给C函数的技巧是,将带有 void *
指针传递给C,然后让C代码将其传递回静态回调函数:
A trick to passing member functions to C functions requires passing an additional void*
pointer with the "registration" record, and having C code pass it back to your static callback functions:
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
:
C code would need to pass the value of context
to fn1
and fn2
:
cs.fn1(cs.context, 123);
cs.fn2(cs.context, 456);
这篇关于将C ++成员函数传递给C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!