从c++向目标c调用回调函数

Calling callback function from c++ to objective c

本文关键字:调用 回调 函数 目标 c++      更新时间:2023-10-16
  1. 我在我的目标c项目中使用c++库
  2. 我集成了c++库,并实现了.mm文件来桥接c++和objectivec
  3. 使用这个.mm桥,我可以成功地从目标c调用c++函数。

  4. 问题是,给定c++库中的方法返回的是nothing,即Void。例如void login(const char*电子邮件,const char*password);

  5. 这个c++库实现了回调函数来了解这个登录方法的结果。

示例:

class DemoApp : public XClass
{
int urandomfd;
public:
uint32_t dstime(void);
FileAccess* newfile();
void request_error(MegaClient*, error);
void login_result(MegaClient*, error);
void users_updated(MegaClient*, User**, int);
void nodes_updated(MegaClient*, Node**, int);
int prepare_download(MegaClient*, Node*);
void share_result(MegaClient*, int, error);
void account_details(MegaClient*, AccountDetails*, int, int, int, int, int, int);
void topen_result(MegaClient*, int, error);
void topen_result(MegaClient*, int, string*, const char*, int);
void transfer_update(MegaClient*, int, off_t, off_t, uint32_t);
void transfer_error(MegaClient*, int, int, int);
void transfer_failed(MegaClient*, int, error);
void transfer_failed(MegaClient*, int, string&, error);
void transfer_limit(MegaClient*, int);
void transfer_complete(MegaClient*, int, chunkmac_map*, const char*);
void transfer_complete(MegaClient*, int, const byte*, const byte*, SymmCipher*);
void changepw_result(MegaClient*, error);
void reload(MegaClient*, const char*);
void notify_retry(MegaClient*, int);
void debug_log(MegaClient*, const char*);
DemoApp();
};
  1. 所以现在我关心的是,我应该如何以及何时调用目标C库中的这些CALLBACK函数,在我看来,它们是在C++库中内部调用的。

  2. 这是我的wrapper.mm文件,包装c++方法,需要调用目标c。

    -(void)包装登录:(NSString*)电子邮件:(NSString*)pwd{

    self.wrappedModelAccessMega->登录([email-UTF8String],[pwd-UTF8String]);//没有返回,因为来自c++库的登录功能没有返回任何内容,即无效

    }

  3. 我已经花了一段时间来研究它,并且已经努力将这个库集成到我的目标C库中,现在由于这些回调函数,我一直坚持使用它。请举一个小例子,展示我应该如何使用c++的回调函数,包装它,并在我的目标c中调用,以获取/知道我的登录函数的结果/返回,这对我来说会很好。

简单的答案是:

  1. 编写回调函数背后的逻辑是,它们应该得到调用当响应来自服务器或某个事件发生时在内部
  2. 如果你想使用它,你需要实现逻辑,比如说存储值,并在回调后返回此变量函数被调用。(不推荐)
  3. 如果你想在其他平台上使用这个回调函数,比如目标C然后将这个回调函数与Delegates桥接起来。(推荐)

感谢Jaggu先生帮助我了解了这一点。