成员函数用于回调函数

时间:2021-08-23 11:52:15
【文件属性】:
文件名称:成员函数用于回调函数
文件大小:17KB
文件格式:ZIP
更新时间:2021-08-23 11:52:15
thunk技术 如qsort 等函数需要函数指针才能回调 用此函数库可以将成员函数指针转为普通函数指针 测试代码如下 #include #include #include #include #include #include using cmpfunc = int(__cdecl*)(const void*, const void*); using DebugArrayFunc = void(__stdcall *)(std::string &out;); #include "thunk.h" class MySort { public: int Rule; MySort(int a):Rule(a){} // 回调函数 template int __cdecl sort(const void* a, const void* b); }; class Test { public: std::vector mm; void Sort(int (*comp)(const void *,const void *)) { return qsort(mm._Myfirst,mm.size(),sizeof(int),comp); } void Entry(DebugArrayFunc func) { std::string string; cmpfunc comp; TemplateThunk athunk; // 正序 comp = (cmpfunc)athunk.GetCall(&MySort;::sort, &MySort;(0)); Sort(comp); func(string); std::cout << string << std::endl; // 逆序 comp = (cmpfunc)athunk.GetCall(&MySort;::sort, &MySort;(1)); Sort(comp); func(string); std::cout << string << std::endl; } }; class CallBack { public: std::vector *pthis; CallBack(std::vector *ff):pthis(ff){} void __stdcall DebugArray(std::string &out;) { char buff[100]; char *aa = buff; for each (auto a in *pthis) { aa += sprintf(aa, "%d ", a); } out.assign(buff); } }; void main() { TemplateThunk athunk; Test tt; tt.mm = { 1, 3, 7, 8, 5, 6, 4, 2, 3, 10 }; tt.Entry(athunk.GetCall(&CallBack;::DebugArray,&CallBack;(&tt;.mm))); } template int __cdecl MySort::sort(const void* a, const void* b) { return Rule ? *static_cast(a)-*static_cast(b) : *static_cast(b)-*static_cast(a); }
【文件预览】:
Release
----Thunk.dll(8KB)
----Thunk.lib(3KB)
thunk.h
thunklib.vcxproj
thunklib.sln
main.cpp
Debug
----Thunk.dll(31KB)
----Thunk.lib(3KB)

网友评论