Assign C++ member function to C function pointer(将 C++ 成员函数赋值给 C 函数指针)
问题描述
我有一个带有如下结构的 C 库:
I have a C library with a struct like this:
struct A {
void process(){
doProcess();
};
void (*doProcess)(void);
}
现在,我有一个类
class B
{
public:
B(): a(){
a.doProcess = print();
}
void print(){
// do anything
}
private:
A a;
}
这是行不通的,因为 print 是一个成员函数,必须在 B 的对象上调用.因此我尝试使用 boost::bind 函数:
This cannot work since print is a member function and has to be called on an object of B. Thus I tried to use the boost::bind function:
a.doProcess = boost::bind(&A::print, this)
这也不起作用.
我还尝试修改 C 库并将函数指针定义替换为 boost::function 定义.但是随后编译器抱怨没有找到包含在boost/function.h"中的".
I also tried to modify the C Library and replace the function pointer definition with a boost::function definition. But then the compiler complains about not finding "" which is included in "boost/function.h".
是否有(简单/提升)方法将成员函数分配给结构的指针?
Is there a (easy/boost) way of assigning a member function to the struct's pointer?
推荐答案
您根本无法做到这一点.成员函数有一个隐式的 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.
这篇关于将 C++ 成员函数赋值给 C 函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 C++ 成员函数赋值给 C 函数指针
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01