From 58ea520a63d66c526ffe6ab01a68dff84653e707 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sun, 10 Jan 2021 18:21:01 +0800 Subject: [PATCH] feat: dotalib --- __ffi/dotalib/dotalib.h | 6 +++++- __ffi/dotalib/justfile | 10 ++++++++++ __ffi/dotalib/src/lib.rs | 21 +++++++++++++++++++-- __ffi/dotalib/test.c | 6 +++++- 4 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 __ffi/dotalib/justfile diff --git a/__ffi/dotalib/dotalib.h b/__ffi/dotalib/dotalib.h index f96ab1d..e0dd3f8 100644 --- a/__ffi/dotalib/dotalib.h +++ b/__ffi/dotalib/dotalib.h @@ -5,4 +5,8 @@ #include -void print_hello_world(void); +const char *get_str(void); + +char *get_str_mut(void); + +void println(const char *str); diff --git a/__ffi/dotalib/justfile b/__ffi/dotalib/justfile new file mode 100644 index 0000000..50dd480 --- /dev/null +++ b/__ffi/dotalib/justfile @@ -0,0 +1,10 @@ +_: + @just --list + +bindgen: + cbindgen --config cbindgen.toml --crate dotalib --lang c --output dotalib.h + +build: bindgen + cargo build + gcc -Ltarget/debug/ -ldota test.c + diff --git a/__ffi/dotalib/src/lib.rs b/__ffi/dotalib/src/lib.rs index 6fa6b6c..3650fb2 100644 --- a/__ffi/dotalib/src/lib.rs +++ b/__ffi/dotalib/src/lib.rs @@ -1,4 +1,21 @@ +use std::{ffi::{CStr, CString}, os::raw::c_char}; + #[no_mangle] -pub unsafe extern "C" fn print_hello_world() { - println!("Hello World!"); +pub unsafe extern "C" fn println(str: *const c_char) { + let c_str = CStr::from_ptr(str).to_str().unwrap(); + println!("{}", c_str); } + +#[no_mangle] +pub unsafe extern "C" fn get_str_mut() -> *mut c_char { + let c_string = CString::new("hello world!").expect("Error!"); + c_string.into_raw() +} + + +#[no_mangle] +pub unsafe extern "C" fn get_str() -> *const c_char { + let c_string = CString::new("hello world!").expect("Error!"); + c_string.as_ptr() +} + diff --git a/__ffi/dotalib/test.c b/__ffi/dotalib/test.c index ac50146..bc93a47 100644 --- a/__ffi/dotalib/test.c +++ b/__ffi/dotalib/test.c @@ -1,5 +1,9 @@ +#include #include "dotalib.h" int main(int argc, char** argv) { - print_hello_world(); + println("hello world"); + char* s = get_str_mut(); + printf("Get: %s\n", s); + free(s); }