Skip to content
Permalink
Browse files
Implement hello2
  • Loading branch information
yutannihilation committed Sep 15, 2020
1 parent 68d2b2b commit a42346c728a408fb1b2e6e7522082e19ec5b8a04
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
@@ -10,6 +10,14 @@ hello <- function() {
.Call(hello_wrapper)
}

#' @export
#' @rdname hellorust
#' @examples hello()
#' @useDynLib hellorust hello_wrapper2
hello2 <- function(name) {
.Call(hello_wrapper2, name)
}

#' @export
#' @rdname hellorust
#' @examples random()
@@ -5,6 +5,7 @@ extern "C" {
#endif

char * string_from_rust();
char * string_from_rust2(const char*);
int32_t random_number();
void run_threads();

@@ -1,5 +1,5 @@
use std;
use std::ffi::CString;
use std::ffi::{CStr, CString};
use std::os::raw::c_char;

#[no_mangle]
@@ -9,3 +9,18 @@ pub extern fn string_from_rust() -> *const c_char {
std::mem::forget(s);
p
}

// Utility function to convert c_char to string
fn c_char_to_string(c: *const c_char) -> String {
unsafe { CStr::from_ptr(c).to_string_lossy().into_owned() }
}

#[no_mangle]
pub extern fn string_from_rust2(c_name: *const c_char) -> *const c_char {
let name = c_char_to_string(c_name);

let s = CString::new(format!("Hello {} !", name)).unwrap();
let p = s.as_ptr();
std::mem::forget(s);
p
}
@@ -10,6 +10,12 @@ SEXP hello_wrapper(){
return Rf_ScalarString(Rf_mkCharCE(string_from_rust(), CE_UTF8));
}

SEXP hello_wrapper2(SEXP name){
char* res = string_from_rust2(Rf_translateCharUTF8(STRING_ELT(name, 0)));
return Rf_ScalarString(Rf_mkCharCE(res, CE_UTF8));
}


SEXP random_wrapper(){
return Rf_ScalarInteger(random_number());
}
@@ -22,6 +28,7 @@ SEXP threads_wapper(){
// Standard R package stuff
static const R_CallMethodDef CallEntries[] = {
{"hello_wrapper", (DL_FUNC) &hello_wrapper, 0},
{"hello_wrapper2", (DL_FUNC) &hello_wrapper2, 0},
{"random_wrapper", (DL_FUNC) &random_wrapper, 0},
{"threads_wapper", (DL_FUNC) &threads_wapper, 0},
{NULL, NULL, 0}

0 comments on commit a42346c

Please sign in to comment.