diff --git a/.gitignore b/.gitignore index 927f10c..fd1065e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ /to-json/target/ /cmake-build-debug/ /cmake-build-release/ +/src/to-json/target/ diff --git a/src/demo.c b/src/demo.c new file mode 100644 index 0000000..4cc3f16 --- /dev/null +++ b/src/demo.c @@ -0,0 +1,18 @@ +#include +#include "to_json.h" + +int main() { + printf("start demo\n"); + + char raw_string[] = "hello"; + + const char *json_content = to_json_rust(raw_string); + + printf("return content -> `%s`\n", json_content); + + free_rust_string(json_content); + + printf("rust string free success\n"); + + return 0; +} diff --git a/src/to-json/Cargo.lock b/src/to-json/Cargo.lock new file mode 100644 index 0000000..3efbc0d --- /dev/null +++ b/src/to-json/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "to-json" +version = "0.1.0" diff --git a/src/to-json/Cargo.toml b/src/to-json/Cargo.toml new file mode 100644 index 0000000..a8c79b7 --- /dev/null +++ b/src/to-json/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "to-json" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/to-json/src/lib.rs b/src/to-json/src/lib.rs new file mode 100644 index 0000000..1ece23a --- /dev/null +++ b/src/to-json/src/lib.rs @@ -0,0 +1,15 @@ +use std::ffi::{c_char, CStr, CString}; + +#[no_mangle] +pub unsafe extern "C" fn to_json_rust(content: *const c_char) -> *const c_char { + let content: &str = CStr::from_ptr(content).to_str().unwrap(); + + println!("Raw content -> {}", content); + + CString::new(content).unwrap().into_raw() +} + +#[no_mangle] +pub unsafe extern "C" fn free_rust_string(string: *const c_char) { + let _ = CString::from_raw(string as *mut _); +} diff --git a/src/to-json/to_json.h b/src/to-json/to_json.h new file mode 100644 index 0000000..5dff661 --- /dev/null +++ b/src/to-json/to_json.h @@ -0,0 +1,8 @@ +#include +#include +#include +#include + +const char *to_json_rust(const char *content); + +void free_rust_string(const char *string);