且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将C ++成员函数分配给C函数指针

更新时间:2022-05-21 23:59:58

您根本无法做到这一点.成员函数具有隐式this参数,该参数是指向在其上调用函数的对象的指针.不将B *作为参数的函数将永远无法在特定的B实例上运行,并且不将这一点作为其第一个参数的函数永远不能具有与类方法相同的签名.有关此问题的更多详细信息和解决方法的示例,请阅读:

You simply cannot do this. Member functions have an implicit this argument that is a pointer to the object on which the function is being called. A function that does not take a B* as an argument will never manage to run on a specific B instance and a function that does not take this point as its first argument can never have the same signature as a class method. For more details on this problem and an example of a workaround read:

https://isocpp.org/wiki/faq /pointers-to-members#memfnptr-vs-fnptr

请注意答案底部的注释,说明如何以这种方式使用静态成员函数.

Pay attention to the note at the bottom of the answer on how static member functions can be used in such manner.

纯C ++项目可以使用std :: function& std :: bind可以满足您的要求,但是C ++项目使用的C库无法使用这些类型.

Pure C++ projects can use std::function & std::bind to achieve what you are asking about, but a C library used by a C++ project cannot work with these types.