[완료] 함수 포인터를 멤버 변수로 저장할수 있나요?

kleinstein의 이미지

요즘 콜백함수때문에 머리가 터질것 같습니다..

아무튼...

제가 궁금한건,

다른 객체(A)에서 전달받은 함수 포인터를 현재의 객체(B)내의 멤버 변수로 저장할수 있나요?

그런다음 나중에 멤버 변수로 저장된 이 함수 포인터를 다시 마치 함수처럼사용하는게 가능한지요?

//////////////////////////
#include<B.h>
class A
{
   static myFunction(string a);
   void do();
}
 
A::do()
{
   set_callback(myFunction);   
}
 
 
//////////////////////////
 
 
class __declspec(dllexport) B
{
   void* var;  // <-- ??
   string hallo;
 
   set_callback((*caller)(string b));
   void anotherDo();
}
 
B::set_callback((*caller)(string b))
{
   var = caller;    // <-- ??
}
 
B::anotherDo()
{
   ((*)(string b)var)(hallo);  // <-- ??
}

위에서 B::anotherDo() 같은게 가능한건지 모르겠네요..

neogeo의 이미지

dll 로 빼신 부분의 소스가 일단 caller 의 type define 도 안보이고.. 뭐라고 말하기 힘든 소스네요.

caller 를

 typedef void (*caller)(string);

라고 보고,

위와 같이 function pointer 의 type 을 정확히 안다는 가정하에 static member function 을 이용하는 것 이라면 당연히 가능합니다.

B::anotherDo() 쪽에서 caller 로 casting 을 해주시면 원하는 결과를 얻으실 수 있습니다.

var 가 void* 라서 그런데, 굳이 void* 로 하시기 보단 caller type 으로 선언하시면 좀 더 쉽게 이용이 가능하겠죠.

#include <string>
#include <iostream>
 
using namespace std;
 
typedef void (*caller)(string);
 
class A
{
    public:
        static void myFunction(string a);
};
 
void A::myFunction(string a)
{
    cout << "A myFunction( " << a << " ) " << endl;
}
 
class B
{
    caller var;
    string hallo;
 
public:
    void set_callback(caller);
    void anotherDo();
};
 
void B::set_callback(caller x)
{
   var = x;
}
 
void B::anotherDo()
{
   var("hello");
}
 
int main(int argc , char** argv )
{
    B b;
    b.set_callback(&A::myFunction);
    b.anotherDo();
}

만약 저렇게 주어지는 static member function 의 원형을 모른체로 void* 로만 받아야 한다면 set_callback 에 받는 인자가 caller

라는 것을 대충 알 수 있게 int 변수에 enum valvue 라도 정의해서 값을 저장해 두시는게 나중을 위해 좋을 수 있습니다.

Neogeo - Future is Now.

Neogeo - Future is Now.

kleinstein의 이미지

정말 감사합니다.

이렇게 되는군요!

다시한번 감사드립니다!!