用裸函数指针调用成员函数 [英] Call a member function with bare function pointer

查看:69
本文介绍了用裸函数指针调用成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一个对象和一个指向成员的裸函数指针,那么调用成员函数的最佳方法是什么?本质上,我想使用 thiscall 调用约定来调用函数指针.

What's the best way to call a member function if you have an object and a bare function pointer pointing to the member? Essentially I want to call the function pointer with thiscall calling convention.

背景:我正在共享库中动态查找符号,获得了工厂函数指针和指向要调用的某个成员函数的指针.成员函数本身不是虚拟的.我无法控制共享库,只有二进制文件.

Background: I'm looking up symbols in a shared library dynamically, obtaining a factory function pointer and a pointer to a certain member function I want to call. The member function itself is not virtual. I have no control over the shared library, I just have the binary.

示例:

typedef void * (*GenericFptr)();
GenericFptr lookup(const char *);

class CFoo;

GenericFptr factoryfn(lookup("CFoo factory function"));
CFoo *foo = reinterpret_cast<CFoo *>(factoryfn());

GenericFptr memberfn(lookup("CFoo member function"));

// now invoke memberfn on foo

当前,我正在使用 union 将函数指针转换为指向成员函数的指针.这很丑陋,并创建了对编译器实现细节的依赖项:

Currently I'm using an union to convert the function pointer to a pointer to member function. It's ugly and creates dependencies to compiler implementation details:

class CFoo {
  public: 
  void *dummy() { return 0; }
};
typedef void * (CFoo::*FooMemberPtr)();

union {
  struct {
    // compiler-specific layout for pointer-to-member
    void *x, *y;
    GenericFptr ptr;
  } fnptr;
  FooMemberPtr memberfn;
} f;

f.memberfn = &CFoo::dummy; // init pointer-to-member
f.fnptr.ptr = memberfn;    // rewrite pointer

void *result = (foo->*f.memberfn)();

推荐答案

不幸的是,成员函数指针比标准函数指针具有更多信息,当您获得标准函数指针时,将其转换为成员函数指针实际上是试图凭空产生额外的数据.

Unfortunately a member function pointer has more information than a standard function pointer, and when you get the standard function pointer, converting it to a member function pointer would effectively be trying to generate extra data out of thin air.

我不认为有任何便携式方法可以执行您要尝试的操作,尽管如果工会看起来可行,您可能会避免这样做.同样,您将需要了解要用于构建Bode的每个编译器的这些方法的表示形式和调用约定.

I don't think there's any portable way to do what you're attempting, although if the union appears to work you could probably get away with that. Again, you would need to know the representation and calling convention for these methods for each compiler you wish to use to build the bode.

如果您知道成员函数的名称,为什么不能仅执行 foo-> dummy()?否则,查找函数需要提供完整的成员函数指针,否则库将必须提供带有普通函数的C包装器接口,此指针可以传递给该函数.

If you know the member function's name, why can't you just do foo->dummy() for example? Otherwise either the lookup function needs to provide a full member function pointer or the library would have to provided a C wrapper interface with normal functions to which a this pointer can be passed.

这篇关于用裸函数指针调用成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆