Racket FFI: C function that takes a pointer to a function

I would like to bind to the C abc function, whose signature is:

 int abc(void (*)(int)) 

those. it takes a pointer to a function. This callback accepts an int and has a return type of void .

What is the correct spell in Racket?

+4
source share
1 answer

Here is an example of a similar binding: let's say that we want to associate the callTwice function with a signature:

 int callTwice(int (*)(int)); 

and with a silly C implementation:

 int callTwice(int (*f)(int)) { return f(f(42)); } 

Here's what the Racket FFI binding looks like:

 (define call-twice (get-ffi-obj "callTwice" the-lib (_fun (_fun _int -> _int) -> _int))) 

where the-lib is the FFI-linked library that we get from ffi-lib . Here we see that the first call-twice argument itself is (_fun _int -> _int) , which is the type of function pointer we want for my example.

This means that technically we could write this:

 (define _mycallback (_fun _int -> _int)) (define call-twice (get-ffi-obj "callTwice" the-lib (_fun _mycallback -> _int))) 

to make it easier to see that call-twice takes a callback as a single argument. For your case, you probably want (_fun _int -> _void) for the value of your callback type.

A fully developed example can be found here: https://github.com/dyoo/ffi-tutorial/tree/master/ffi/tutorial/examples/call-twice . Run pre-installer.rkt in this directory to create the extension, and then test it by running test-call-twice.rkt .

+7
source

Source: https://habr.com/ru/post/1485128/


All Articles