How to call function in share library
I try to use external_call to load library and symbol. But I don't know how to call it like C . How to do it in Mojo ??
fn main():
let data = "./libexample.so"
let data_ptr = to_char_ptr(data)
#let flag: c_int = RTLD_NOW
let flag: c_int = RTLD_LAZY
let hdl = external_call["dlopen", c_void, Pointer[c_char], c_int](data_ptr, flag)
print("hdl ", hdl)
if hdl == 0:
let error_msg_cstr = external_call"dlerror", Pointer[c_char]
let msg = StringRef(error_msg_cstr.bitcastInt8)
print("lib_handler error ", msg)
else:
let a = external_call"dlerror", Pointer[c_char]
print("lib_handler ", hdl)
let sym_name = to_char_ptr("hello_world")
let fun_sym = external_call["dlsym", c_void, c_void, Pointer[c_char]](hdl, sym_name)
print("fun_sym", fun_sym)
print("end of main()")
5 Replies
@sa-code do you know a current way to work with a C-shared lib?
Hm it looks like @ziyu4huang has a lot of it figured out already. What's the error that you're running into?
mmm but where is coming from
to_char_ptr
?
I know that is planned to have something like
(from docs)
but right now I need a more explicit example of how to make this 🥲Yeah the documentation around it isn't great - I have personally only used the c stdlib so far
Although I just saw this post from @ihnorton https://github.com/ihnorton/mojo-ffi
GitHub
GitHub - ihnorton/mojo-ffi
Contribute to ihnorton/mojo-ffi development by creating an account on GitHub.