What's the protocol for calling Raku code from C code?

Another approach could be to save a callback statically in the C library, for example (libmylib.c):

#include <stdio.h>

static int (*raku_callback)(char *arg);

void set_callback(int (*callback)(char * arg)) {
    printf("In set_callback()..\n");
    raku_callback = callback;
}

void foo() {
    printf("In foo()..\n");
    int res = raku_callback("hello");
    printf("Raku return value: %d\n", res);
}

Then from Raku:

use v6;
use NativeCall;

sub set_callback(&callback (Str --> int32)) is native('./libmylib.so') { * }
sub foo() is native('./libmylib.so') { * }

sub callback(Str $str --> Int) {
    say "Raku callback.. got string: {$str} from C";
    return 32;
}

set_callback(&callback);
foo();

Output:

In set_callback()..
In foo()..
Raku callback.. got string: hello from C
Raku return value: 32

Raku is a compiled language; depending on the implementation you've got, it will be compiled to MoarVM, JVM or Javascript. Through compilation, Raku code becomes bytecode in the corresponding virtual machine. So it's never, actually, binary code.

So my answer would be that it's not possible, since there are no binary endpoints created for C functions. However, there's NativeCall, so you can call C from Raku. You might want to rearrange your code, handle connections from Raku, and call whatever business logic you have in C from there.

Tags:

Raku