创建一个__cdecl以在 C++ 上__thiscall包装函数

Create a __cdecl to __thiscall wrapper function on c++

本文关键字:C++ thiscall 包装 函数 以在 cdecl 一个 创建      更新时间:2023-10-16

我需要动态创建一个函数,该函数可以使用__cdecl调用约定由外部库调用,然后将调用重定向到类上的方法,有效地充当__thiscall调用约定的代理。

主要思想是这个程序(program1(应该从外部应用程序(program2(接收一个函数指针,将其打包成一个可以查询我们的对象(program1(以了解是否应该调用program2,然后将其传递给库。

我对此类的标头应该是什么样子有一个模糊的概念

template <typename F, class C>
class this_call_wrapper
{
public:
    // Creates a wrapper function that calls `operator()` on `object`
    // `operator()` should take the same arguments as `F`
    this_call_wrapper(const C* object);
    // Deallocates memory used by this and the wrapper
    ~this_call_wrapper();
    // Returns the pointer to the function wrapper
    F* get_wrapper();
private:
    C* object;
    F* wrapper;
};

是否有任何库提供类似的功能?如果没有,我如何在C++中实现这一点?

我发现libffcall是解决这些问题的最合适的解决方案。在汇编/机器代码上构造闭包也是一个有效的选择,但是使用 libffcall 实现同样的事情是多么容易和可移植,我认为你不想弄乱前者,除非你有某种(非常限制性的(大小约束你的二进制文件。

这是最终的解决方案。