gpt4 book ai didi

ios - 在 C 中抛出 Swift 可以捕获的事件

转载 作者:行者123 更新时间:2023-11-30 13:54:53 26 4
gpt4 key购买 nike

我使用带有静态回调方法的 C 代码的静态库。指向该方法的指针被分配给一个变量。每次库调用这个函数时,我也需要快速处理这个事件。一个最小的例子是:

static void onEventXYZ(int x, int y, struct z);

int anFunction(){
libraryFile.attribute = &onEventXYZ;
}


//a C callback function
static void onEventXYZ(int x, int y, struct z){
//function body
}

我的问题是我不知道如何在 swift 类中对这样的回调使用react。值得注意的是,当应用程序可能处于后台时,我还需要对此回调使用react。

是否可以抛出 swift 能够捕获和处理的事件或信号?

最佳答案

假设您有一个函数需要指向该回调函数的指针...

void doSomething(void (*callback)(int, int)); // int parameters just for example

...它被翻译成 Swift 如下:

func doSomething(callback: @convention(c) (Int, Int) -> Void)

这意味着您可以使用任何函数作为回调,只要它与 @convention(c) 标准兼容即可:

doSomething {
print($0)
print($1)
}

// or

func onSomething(i: Int, j: Int) {
print(i)
print(j)
}

doSomething(onSomething)

// or

let onSomething: (Int, Int) -> Void = { i, j in
print(i)
print(j)
}

doSomething(onSomething)

关于ios - 在 C 中抛出 Swift 可以捕获的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33757736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com