Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Swift not work with function pointers?

Tags:

c

xcode

ios

swift

lua

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.

like image 309
Mike Avatar asked Jun 06 '14 18:06

Mike


People also ask

Can Swift call C functions?

In Swift, you can call C variadic functions, such as vasprintf(_:_:_:) , using the Swift getVaList(_:) or withVaList(_:_:) functions.

Can you pass a function as a parameter in Swift?

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.

Can we use pointer in function?

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.

How do you assign a variable to a function in Swift?

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.


1 Answers

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.

like image 56
Jim Hayes Avatar answered Sep 28 '22 02:09

Jim Hayes