2012-06-25 7 views
1

많은 예제가 있지만 내 문제에 대한 해결책을 찾을 수없는 것 같습니다. 나는 StartGetFoos()가 호출멤버 함수에 대한 포인터 전달

class FooSource{ 
    ... 

    void StartGetFoos(void (*callback)(vector<IFoo*>*, IAsyncResult)); 
    ... 
} 

,이 콜백을 절약하여 FOOS를 얻기 위해 수행 요청을해야합니다. 요청이 완료되면 (약 30 초 소요) 저장된 콜백이 결과와 함께 호출됩니다. 이 메서드의 서명을 변경할 수 없습니다.

는 다른 곳 난 당신이 멤버 함수를 사용할 수 있도록하는 this 포인터를받을 수 있도록 서명 void (*callback)(vector<IFoo*>*, IAsyncResult)에 아무데도 없다 클래스를

class FooUser { 
    ... 

    void FooUser::MyCallback(vector<IFoo*>* foos, IAsyncResult result) 
    { 
      // marshall to UI thread and update UI 
    } 

    void init() 
    { 
     fooUser->StartGetFoos(??????); 
     // how do I pass my callback member function here? 
    } 
} 
+0

관련 : http://stackoverflow.com/questions/1738313/c-using-class-method-as-a-function-pointer-type –

답변

3

있습니다. 대신 당신이 static 멤버 함수를 사용해야합니다 :

class FooUser { 
    static void MyCallback(vector<IFoo*>* foos, IAsyncResult result) 
    { 
      // marshall to UI thread and update UI 
    } 

    void init() 
    { 
     fooUser->StartGetFoos(&FooUser::MyCallback); 
    } 
}; 

여기에서의 문제는 FooUser에 인스턴스 데이터에 액세스 할 수 없을 것입니다; 이것은 문제 일 수도 있고 아닐 수도 있습니다.

API가 얼마나 잘 설계되었는지에 따라 인스턴스 포인터를 전달할 수있는 방법이있을 수 있습니다. IAsyncResult result을 통해

+0

당신이 정적 멤버 함수를 사용하는 방법을 확장 할 수 이 경우? 나는 [이 게시물] (http://stackoverflow.com/questions/400257/how-can-i-pass-a-class-member-function-as-a-callback) 일찍 찾고 있었고 유망한 보였지만 couldn 내 상황에 맞는 것들을 변형시키지 마라. 도와 주셔서 감사합니다. –

+1

@ProfessorChaos에서 정적 멤버 함수를 사용하여 다른 비 정적 멤버 함수를 호출합니다. 이렇게하려면 정적 함수는 어딘가에서 객체 포인터를 가져와야합니다. 하나 이상의 콜백이없는 경우에는 정적 멤버 포인터 변수를 사용해야합니다. –

2

IAsyncResult가 get이 전달 된 데이터 구조이고 작업을 위해 다시 나왔다면 사용자의 정보로 확장 할 수 있습니다. ecatmur 말한대로

class MyAsyncResult : public IAsyncResult 
{ 
public: 
    MyAsyncResult(FoorUser *sender) : sender(sender){} 
    FooUser *sender; 
}; 

그런 다음, 당신은 콜백에 대한 정적 멤버 함수를 지정할 수 있습니다,하지만 당신은 afterwords 호출되는 정규 멤버 함수를 만들 수 있습니다

정적 멤버 함수가에 액세스 할 수 없습니다를 클래스 멤버이지만 일반적인 C 함수가 일반적으로 필요할 콜백으로 지정할 수 있습니다.

class FooUser 
{ 
    // static with no access to class members, but can be specified as a callback. 
    static void MyCallback(vector<IFoo*>* foos, IAsyncResult *result) 
    { 
      MyAsyncResult *res = (MyAsyncResult*)result; 
      res->sender->MyCallback(foos, result); 
    } 

    void MyCallback(vector<IFoo*>* foos, IAsyncResult *result) 
    { 
      // handle the actual callback here 
    } 

    void init() 
    { 
     IAsyncResult *res = new MyAsyncResult(this); 
     fooUser->StartGetFoos(&foos, res); 
    } 
} 
관련 문제