Rust call C dll

add.h
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

__declspec(dllexport) int add(int a, int b, char* str);

#ifdef __cplusplus
}
#endif

add.cpp
#include "add.h"
#include 
int add(int a, int b, char* str) {
    strcpy(str, u8"hello, world! 你好!~");
    return a + b;
}

Cargo.toml
[dependencies]
libloading = "0.8"
libc = "0.2.153"

main.rs
use libc::*;
use libloading::{Library, Symbol};
type FnAdd = unsafe extern fn(a: i32, b: i32, c: *mut c_char) -> i32;
unsafe {
	let lib = Library::new("TestDll.dll").unwrap();
	let func_add: Symbol = lib.get(b"add").unwrap();
	let mut str_out = [0u8; 256];  // 分配存储空间
	println!("{}", func_add(1, 2, str_out.as_mut_ptr() as *mut i8));
	let sv = &str_out[0..strlen(str_out.as_ptr() as *const i8)]; // 通过strlen构造对应字符串的数组
	let s = String::from_utf8_unchecked(sv.to_vec()); // 字符串使用utf8编码的u8
	println!("{}", s);
	format!("{}", s)
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

20 + 15 =