x[package]
name = "test_ffi"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
libc = "0.2.149"
xxxxxxxxxx
use libc::{c_char, c_int, c_void};
use std::ffi::CString;
fn main() {
unsafe {
// 加载 C 库
let path = CString::new("libc.so.6").unwrap();
let lib = libc::dlopen(path.as_ptr(), libc::RTLD_LAZY);
if lib.is_null() {
panic!("Failed to open libc");
}
// 获取 C 库中的函数指针
let puts = CString::new("puts").unwrap();
let puts_fn: *mut c_void = libc::dlsym(lib, puts.as_ptr());
if puts_fn.is_null() {
let msg = libc::dlerror();
if !msg.is_null() {
let msg = std::ffi::CStr::from_ptr(msg).to_string_lossy().to_string();
println!("Failed to find puts function: {}", msg);
}
}
// 将函数指针转换为函数类型
let puts: extern "C" fn(*const c_char) -> c_int = std::mem::transmute(puts_fn);
// 调用 puts 函数
let str = CString::new("Hello, World!\n").unwrap();
puts(str.as_ptr());
// 关闭 C 库
libc::dlclose(lib);
}
}