【问题标题】:Passing objc block to function将 objc 块传递给函数
【发布时间】:2019-03-29 12:11:03
【问题描述】:

已经为此苦苦挣扎了 2 天,我对 C 语言不是很熟练。所以,使用以下语法将 objc 函数映射到 C 函数

extern int32_t createWallet(void (*fn)(int32_t handle, int32_t errCode)

但不知道如何传递类似块的函数。一直在尝试通过

void (^ createWalletCallback)(int32_t t, int32_t e) = NULL;
createWalletCallback = ^void(int32_t t, int32_t e){
    /// some code here
}

但没有成功。你能否请至少指出我要改变什么?谢谢

【问题讨论】:

标签: objective-c objective-c-blocks


【解决方案1】:

这似乎是 Is there a way to wrap an ObjectiveC block into function pointer? 的副本,其中的建议是“不要这样做”。

相反,你能不使用普通的 C 函数指针吗?定义一个函数

void createWalletCallback(int32_t t, int32_t e) {
    // some code here, maybe referencing global variables
    // (including a semaphore, if other code needs to wait on the response)
}

然后打电话

createWallet(&createWalletCallback);

【讨论】:

  • 嗯,是的,可以选择在源文件中声明一些静态字段。问题是有 5-6 个回调来完成一个工作单元,因此我希望“捆绑”像 lambdas 这样的函数(来自 .net 世界)
  • 这里的困难在于块是成熟的objective-c对象。 Objective-C 是 C 语言之上的一层,有自己的运行时。 C 函数指针只是 C 函数指针;他们不知道对象属性,当您有一个块时,这些属性用于捕获您无疑想在块内访问的变量。 (希望这是有道理的!)
猜你喜欢
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多