如何在不传递类实例的情况下从静态成员函数调用非静态成员函数

2021-12-23 00:00:00 class static struct c++

我需要从同一个类的静态成员函数调用一个非静态成员函数.静态函数是一个回调.它只能接收 void 作为数据,尽管我传递了一个 char*.所以我不能直接向回调提供类实例.我可以将结构而不是 char 传递给回调函数.任何人都可以提供例如代码以在静态成员函数中使用非静态成员函数.并使用静态成员函数中的结构体来使用类的实例调用非静态成员函数?

I need to call a non static member function from a static member function of the same class. The static function is a callback. It can receive only void as data, though which i pass a char*. So i cannot directly provide the class instance to the callback. I can pass a structure instead of char to the callback function. Can anyone give eg code to use the non static member function in a static member function . and use the structure in the static member function to use the instance of the class to call the non static member function?

推荐答案

通常这样的回调看起来像这样:

Normally such a callback would look like this:

void Callback( void* data)
{
    CMyClass *myClassInstance = static_cast<CMyClass *>(data);
    myClassInstance->MyInstanceMethod();
}

当然,您需要确保数据指向您的类的实例.例如

Of course, you need to make sure, data points to an instance of your class. E.g.

CMyClass* data = new CMyClass();
FunctionCallingMyCallback( data, &Callback);
delete data;

现在,如果我理解正确的话,您还需要传递一个字符*.您可以将两者都包装在一个结构中并在回调中将其解包,如下所示:

Now, if I understand you correctly, you need to also pass a char*. You can either wrap both in a struct and unwrap it in the callback like so:

MyStruct* data = new MyStruct();
data->PtrToMyClass = new CMyClass();
data->MyCharPtr = "test";
FunctionCallingMyCallback( data, &Callback);
delete data->PtrToMyClass;
delete data;


void Callback( void* data)
{
    MyStruct *myStructInstance = static_cast<MyStruct *>(data);
    CMyClass *myClassInstance = myStructInstance->PtrToMyClass;
    char * myData = myStructInstance->MyCharPtr;
    myClassInstance->MyInstanceMethod(myData);
}

或者,如果您可以修改 CMyClass 的定义,请将所有必要的数据放入类成员中,以便您可以像第一个示例中那样使用回调.

or, if you can modify the definition of CMyClass, put all the necessary data in class members, so that you can use a callback as in the first example.

相关文章