M
Modular•14mo ago
ziyu4huang

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
Sarctiann
Sarctiann•13mo ago
@sa-code do you know a current way to work with a C-shared lib?
sa-code
sa-code•13mo ago
Hm it looks like @ziyu4huang has a lot of it figured out already. What's the error that you're running into?
Sarctiann
Sarctiann•13mo ago
mmm but where is coming from to_char_ptr? I know that is planned to have something like
import "math.h"

fn main() raises:
print(cos(2))
import "math.h"

fn main() raises:
print(cos(2))
(from docs) but right now I need a more explicit example of how to make this 🥲
sa-code
sa-code•13mo ago
Yeah the documentation around it isn't great - I have personally only used the c stdlib so far
sa-code
sa-code•13mo ago
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.
Want results from more Discord servers?
Add your server