red-langred-system

Pass Red function pointer to C


I know how to pass a Red/System callback to a C function, but is the same functionality possible to achieve with Red? It is possible to create a Red/System wrapper for a Red function at runtime and pass it to a C function?

I've already looked at a lot of bindings/code here and there, but haven't found anything that solves my problem.

Edit:
Let's say that I've got a simple Red function:

add-numbers: func[a b][a + b]

and I have a Red/System function alias:

callback!: alias function! [a [integer!] b [integer!] return: [integer!]]

Is it possible to somehow convert the above add-numbers function to a callback! using a Red/System wrapper?


Solution

  • You can invoke a Red function! from Red/System using the #call directive. Only simple argument types are auto-converted for you (like numbers and logic value), for the rest, you need to use the Red runtime API to construct and place the function's arguments on the Red stack, and to eventually retrieve the returned value.

    Using #call, you can write wrapper functions in Red/System that can be passed as callbacks to C functions. Here is an example of such wrapper from LibRed's source code.