Swift 不能使用函数指针吗? [英] Does Swift not work with function pointers?

查看:29
本文介绍了Swift 不能使用函数指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Swift 中使用 C 库,但我无法调用任何将函数指针作为参数之一的函数.例如,我尝试在 Swift 中使用的 lua.h 文件的一部分如下所示:

I'm trying to use a C library in Swift, and I'm having trouble calling any function that takes a function pointer as one of it's arguments. For example, part of the lua.h file that I'm trying to use in Swift looks like this:

LUA_API void  (lua_setuservalue) (lua_State *L, int idx);


typedef int (*lua_CFunction) (lua_State *L);

LUA_API void  (lua_callk) (lua_State *L, int nargs, int nresults, int ctx,
                       lua_CFunction k);

我使用桥接头来访问库,并且从我的 Swift 代码中,我可以毫无困难地调用 lua_setuservalue.但是,如果我尝试调用 lua_callk,我会得到使用未解析的标识符 'lua_callk'".如果我从 lua_callk 的声明中删除函数指针,则不会再出现此错误.非常感谢任何帮助.

I use the bridging header to get access to the library, and from my Swift code I can call lua_setuservalue without any trouble. But if I try to call lua_callk I get "use of unresolved identifier 'lua_callk'". If I remove the function pointer from the declaration for lua_callk, I no longer get this error. Any help is quite appreciated.

推荐答案

Apple 从 beta 3 开始提供函数指针,但是它们只能被引用不能被调用.

Apple has made function pointers available as of beta 3, however they can only be referenced not called.

将 Swift 与 Cocoa 和 Objective-C 结合使用

C 函数指针作为 CFunctionPointer 导入 Swift,其中 Type 是一个Swift 函数类型.例如,C 中类型为 int (*)(void) 的函数指针被导入 Swift 作为 CFunctionPointer<() ->Int32>

Function Pointers

C function pointers are imported into Swift as CFunctionPointer<Type>, where Type is a Swift function type. For example, a function pointer that has the type int (*)(void) in C is imported into Swift as CFunctionPointer<() -> Int32>

Beta 3 发行说明 (PDF)

函数指针现在也被导入了,可以被引用和传递.然而,您不能调用 C 函数指针或将闭包转换为 C 函数指针类型.

Function pointers are also imported now, and can be referenced and passed around. However, you cannot call a C function pointer or convert a closure to C function pointer type.

这篇关于Swift 不能使用函数指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆