Call C function from Swift knowing only memory address -


i have simple function in c , pointer gets passed swift.

void callback() {     nslog(@"such pointer…"); } 

how can invoke in swift using only pointer? not invoking – works fine when invoked directly. tried following , different variations signature casting, crashes:

let pointer: unsafepointer<@convention(c)() -> ()> = unsafepointer(bitpattern: …) let callback: @convention(c)() -> () = pointer.memory swift.print(callback) // (function) callback() // handling crash signal 11... 

tried defining callback type typedef void(*callback)(); – same thing:

let pointer: unsafepointer<callback> = unsafepointer(bitpattern: …) let callback: callback = pointer.memory swift.print(callback) // (function) callback() // handling crash signal 11... 

to check works , points right address have objective-c function, works expected when invoked swift callback pointer.

void invokecallback(uintptr_t callback) {     ((void (*)()) callback)(); // such pointer… } 

the same approach in swift: how call c function loaded dylib should work here.

example swift 3 (assuming funcptr unsaferawpointer containing function's address):

// define function type: typealias callbackfunc = @convention(c) () -> void  // convert pointer function type: let callback = unsafebitcast(funcptr, to: callbackfunc.self)  // call function: callback() 

of course type alias must match actual function signature, , function needs "pure" c function (not objective-c method).


Comments

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

arrays - Algorithm to find ideal starting spot in a circle -