Browse Source

feat: rust ffi demo

dev
Dnomd343 2 years ago
parent
commit
6c436af5b2
  1. 1
      .gitignore
  2. 18
      src/demo.c
  3. 7
      src/to-json/Cargo.lock
  4. 11
      src/to-json/Cargo.toml
  5. 15
      src/to-json/src/lib.rs
  6. 8
      src/to-json/to_json.h

1
.gitignore

@ -5,3 +5,4 @@
/to-json/target/ /to-json/target/
/cmake-build-debug/ /cmake-build-debug/
/cmake-build-release/ /cmake-build-release/
/src/to-json/target/

18
src/demo.c

@ -0,0 +1,18 @@
#include <stdio.h>
#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;
}

7
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"

11
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]

15
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 _);
}

8
src/to-json/to_json.h

@ -0,0 +1,8 @@
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
const char *to_json_rust(const char *content);
void free_rust_string(const char *string);
Loading…
Cancel
Save