rs_container_ffi/
vec.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use std::ffi::{CStr, CString};

/// wrap rust Vec<String> new for c
#[no_mangle]
pub extern "C" fn rust_vec_of_str_new() -> *mut Vec<String> {
    return Box::into_raw(Box::new(Vec::<String>::new()));
}

/// wrap rust Vec<String> drop for c
#[no_mangle]
pub extern "C" fn rust_vec_of_str_drop(p: *mut Vec<String>) {
    if p.is_null() {
        return;
    }

    unsafe {
        let _ = Box::from_raw(p); // This will drop and free the memory
    }
}

/// wrap rust Vec<String> push for c
#[no_mangle]
pub extern "C" fn rust_vec_of_str_push(instance: *mut Vec<String>, value: *const i8) {
    if instance.is_null() {
        return;
    }

    let value = unsafe { CStr::from_ptr(value).to_string_lossy().into_owned() };

    let vector = unsafe { &mut *instance };
    vector.push(value);
}

/// wrap rust Vec<String> reverse for c
#[no_mangle]
pub extern "C" fn rust_vec_of_str_reverse(instance: *mut Vec<String>) {
    if instance.is_null() {
        return;
    }

    let vector = unsafe { &mut *instance };
    vector.reverse();
}

/// wrap rust Vec<String> join for c
/// must use rust_c_str_drop to free return value
#[no_mangle]
pub extern "C" fn rust_vec_of_str_join(instance: *mut Vec<String>, sep: *const i8) -> *mut i8 {
    if instance.is_null() {
        return std::ptr::null_mut();
    }

    let sep = unsafe { CStr::from_ptr(sep).to_string_lossy().into_owned() };

    let vector = unsafe { &mut *instance };
    let result = vector.join(&sep);

    let c_str = CString::new(result.clone()).unwrap();
    let ptr = c_str.into_raw();
    return ptr;
}