如何获得“简单”函数指针从成员函数 [英] How to get a "simple" function pointer from a member function
问题描述
我有一个函数指针的问题,我在网上找到的没有帮助我解决这个问题。
I'm having a problem with function pointers and nothing I found on the net helped me to solve this problem.
我有一个来自C API的函数取一个void函数的指针:
I have a function from a C API which take a pointer of a void function :
extern int APIFunction(int,void(* func)(int));
我有一个类,当我调用API函数时,我想要的函数。
I have a class with the function I would like to put when I call the API function.
class MyClass
{
public:
void myFunction(int status, otherAPi arguments...);
};
然后,我创建了一个指向我的成员函数的指针,并创建了我的类的一个新实例
Then, I created a pointer to my member function and created a new instance of my class
typedef void (MyClass::*MyClassFunctionPointer)(int stat, otherAPi arguments...);
MyClassFunctionPointer fctPointer= &MyClass::myFunction;
LicenseSecurity instance;
当我尝试使用我创建的函数指针调用APi函数时出现错误: p>
I get an error when I try to call my APi function with the function pointer I created:
int stat = APIFunction(5, fctPointer ); // -> error 1
int stat = APIFunction(5, instance.*fctPointer ); // -> error 2
我在第一种和第二种情况下分别有错误:
I got errors respectively in the first and second case:
E2034 Impossible to convert 'void (MyClass::*)(int, otherAPITypes...)' into 'void (*) (int, otherAPITypes...)'
E2342 Bad type correspondence in the parameter 'func' ('void (*)(int, otherAPITypes...)' desired, 'void(int, otherAPITypes...)' obtained)
我无法访问API函数,因此我无法修改它。总结问题:如何获得一个简单C函数指针,以便从我的类的成员函数中插入一个函数的参数?
I don't have access to the API function so I can't modify it. To summary the problem: how How to get a "simple" C function pointer to put in argument of a function from a member function of my class?
感谢
推荐答案
不幸的是,你不能。很抱歉。
Unfortunately, you can't. Sorry.
理想情况下,您的API会接受类似 std :: function
或成员函数。但是如果你不能修改API,那么你别无选择,只能提供一个免费的函数。
Ideally, your API would accept something like std::function
that would allow you to wrap free functions or member functions. But if you can't modify the API, then you have no choice but to provide a free function.
这篇关于如何获得“简单”函数指针从成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!