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.
In Swift, you can call C variadic functions, such as vasprintf(_:_:_:) , using the Swift getVaList(_:) or withVaList(_:_:) functions.
Every function in Swift has a type, consisting of the function's parameter types and return type. You can use this type like any other type in Swift, which makes it easy to pass functions as parameters to other functions, and to return functions from functions.
A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.
Swift – Assign Function to a Variable To assign function to a variable in Swift, declare a variable that takes specific set/type of parameters and return a specific type of value. Then we can assign a function that has same type of parameters and return value to this variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With