Does Swift not work with function pointers?

匿名 (未验证) 提交于 2019-12-03 01:14:02

问题:

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); 

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.

回答1:

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

Using Swift with Cocoa and Objective-C

Function Pointers

C function pointers are imported into Swift as CFunctionPointer, 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 Release Notes (PDF)

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.



回答2:

This answer refers to an earlier version of the Swift language and may no longer be reliable.

While C function pointers are not available in Swift, you can still use swift closures which are passed to C functions as blocks.

Doing so requires a few "shim" routines in C to take the block and wrap it in a C function. The following demonstrates how it works.

Swift:

func foo(myInt: CInt) -> CInt {     return myInt }  var closure: (CInt) -> CInt = foo;  my_c_function(closure) 

C:

void my_c_function(int (^closure)(int)) {     int x = closure(10);     printf("x is %d\n", x); } 

Of course what you choose to do with the closure, and how you store and recall it for use is up to you. But this should give you a start.



回答3:

In the Apple documentation it is noted that C function pointers are not imported in Swift.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!