codon
codon copied to clipboard
Execute codon callback function from C issue.
I have encountered a strange problem:
#include <stdint.h>
#include <stdio.h>
typedef int64_t (*fn_foo)(int64_t);
void call_fn(fn_foo fn) {
printf("call_fn: %p\n", fn);
fn(123);
}
gcc -shared -o libfoo.so foo.c
LIBRARY = "libfoo.so"
from C import LIBRARY.call_fn(cobj)
@export
def foo(n: int) -> int:
for i in range(n):
print(i * i)
return n * n
print("+++++++type(foo):", type(foo))
call_fn(foo)
codon build main.py
./main
output:
+++++++type(foo): (item1: (), item2: ())
call_fn: 0x7ff85f10dba8
Bus error: 10
if I comment out print("+++++++type(foo):", type(foo))
, the output is:
call_fn: 0x0
Segmentation fault: 11
Sounds like really weird.
Hi @learnforpractice -- plain functions in Codon can actually have some extra data associated with them so they're not directly ABI compatible with C functions. You can use the __raw__
method to get a plain function pointer, which fixes your example:
call_fn(foo.__raw__())
However I'm not sure why call_fn(foo)
doesn't cause a type error, since foo
is not a cobj
; @inumanag any ideas?
Awesome!