Skip to content

Commit

Permalink
added routine to free the leaked rust CString. (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
CGMossa authored Jun 3, 2024
1 parent 2472f65 commit d85d389
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/myrustlib/api.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ extern "C" {
#endif

char * string_from_rust(void);
void free_string_from_rust(char*);
int32_t random_number(void);
void run_threads(void);

Expand Down
7 changes: 6 additions & 1 deletion src/myrustlib/src/hello.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ use std::ffi::CString;
use std::os::raw::c_char;

#[no_mangle]
pub extern fn string_from_rust() -> *const c_char {
pub extern "C" fn string_from_rust() -> *const c_char {
let s = CString::new("Hello ピカチュウ !").unwrap();
s.into_raw()
}

#[no_mangle]
pub extern "C" fn free_string_from_rust(ptr: *mut c_char) {
let _ = unsafe { CString::from_raw(ptr) };
}
6 changes: 5 additions & 1 deletion src/wrapper.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@

// Actual Wrappers
SEXP hello_wrapper(void){
return Rf_ScalarString(Rf_mkCharCE(string_from_rust(), CE_UTF8));
char* hello_rust = string_from_rust();
SEXP hello_world_string = PROTECT(Rf_mkCharCE(hello_rust, CE_UTF8));
free_string_from_rust(hello_rust);
UNPROTECT(1);
return Rf_ScalarString(hello_world_string);
}

SEXP random_wrapper(void){
Expand Down

0 comments on commit d85d389

Please sign in to comment.