成员函数指针做回调参数总结 踩坑
一、程序升级后,在linux上编译提示错误:
warning: converting from ‘int (MyClass::*)()’ to ‘void(*)()’ [-Wpmf-conversions]
void(*myStoredFunction)(void) = (GENERIC_FUNC_TYPE)memberFunc; //Compiler warning
二、出现这个情况是因为,程序的这个模块是早期开发的,使用的是gcc4开发的,现在升级到gcc7,c++版本兼容性问题,具体解决方法如下:
1:用内联汇编方式,跳过c++,语法检测,x86_64汇编代码如下:
__asm__ (
"mov %1, %0"
:"=r"(addr)
:"r"(&TEST::foo)
);
或者这样更好:
__asm__ ( "" // no instructions
:"=r"(addr)
:"0"(&TEST::foo) // same
register as operand 0
);
2:c++语法转换方式,代码如下:
template <typename C, void (C::*M)()>
void* AsFunc(void* p)
{
(static_cast<C*>(p)->*M)();
}
调用:void (*myExtractedFunction)(void*) = &AsFunc<MyClass, &MyClass::myMemberFunc>;
或者:template
dst_type pointer_cast(src_type src)
{
return*static_cast(static_cast(&src));
}
三、区别总结
参考相关文献
成员函数指针
C++函数指针、函数对象与C++11 function对象对比分析
C++强制类型转换操作符static_cast
C++动态联编实现原理分析
C++类成员函数调用分析
Pointers
to Member Functions
a pointer to member function to
be invoked by the target class without functional
Declares a variable of
a pointer or pointer-to-member type.