将指向成员函数的指针转换为普通指针

将指向成员函数的指针转换为普通指针

本文介绍了将指向成员函数的指针转换为普通指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个这样的类,为简单起见缩短:

Currently I have a class of this kind, shortened for simplicity:

class MyClass {
    public:
        MyClass();
        void* someFunc(void* param);
}

现在我需要调用这种类型的函数(不是任何类的成员,不幸的是我无法更改)但无论如何我都需要调用它:

Now I need to call a function of this kind (not member of any class and which I unfortunately cannot change) but which I need to call anyway:

void secondFunc(int a, int b, void *(*pCallback)(void*));

现在我需要传递一个实例的 someFunc 的地址.

Now I need to pass the address of someFunc of an instance.

一个不起作用的样本:

MyClass demoInstance;
// some other calls
secondFunc( 1, 2, demoInstance::someFunc() );

我也尝试过像这样的演员表:

I've tried also with casts like:

(void* (*)(void*)) demoInstance::someFunc;
reinterpret_cast<(void* (*)(void*))>(demoInstance::someFunc);

如何使用类的成员函数作为参数调用此函数,以便将其用作回调?

How can I call this function with a class' member function as parameter so that this one can use it as callback?

任何想法或评论表示赞赏.谢谢并恭祝安康托比亚斯

Any idea or remark is appreciated. Thanks and regardstobias

推荐答案

C 函数和 C++ 成员函数的区别在于 C 函数使用 cdecl 调用约定,而成员函数使用 thiscall 调用约定(你甚至不能接受他们的地址!).

The difference between a C function and a C++ member function is that C function uses cdecl calling convention, while member functions uses thiscall calling convention (and you can't even take their address!).

据我所知,您实际上希望 secondFunc() 调用特定类实例的成员函数(我们称之为 this).那么,一个特定类的所有实例的成员函数的地址都是相同的.为了将指针传递给对象,您将需要一个侧通道.在这种情况下,它可能是静态变量.或者,如果您想要 MT 支持,则必须使用线程本地存储 (TLS),

As I understand, you actually want that secondFunc() to call the member function of a particular instance of class (let's call it this). Well, addresses of member functions of all the instances of a particular class are the same. In order to pass the pointer to the object, you will need a side channel. In this case it could be static variable. Or, if you want MT support, you'll have to use Thread Local Storage (TLS),

这需要每个 SomeFunc 类型的成员一个回调,但无论如何你都需要一个调度程序.

This requires one callback per SomeFunc-type member, but you would need a dispatcher somewhere anyway.

这篇关于将指向成员函数的指针转换为普通指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:37