Skip to content

Commit a42346c

Browse files
Implement hello2
1 parent 68d2b2b commit a42346c

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

R/hello.R

+8
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ hello <- function() {
1010
.Call(hello_wrapper)
1111
}
1212

13+
#' @export
14+
#' @rdname hellorust
15+
#' @examples hello()
16+
#' @useDynLib hellorust hello_wrapper2
17+
hello2 <- function(name) {
18+
.Call(hello_wrapper2, name)
19+
}
20+
1321
#' @export
1422
#' @rdname hellorust
1523
#' @examples random()

src/myrustlib/api.h

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ extern "C" {
55
#endif
66

77
char * string_from_rust();
8+
char * string_from_rust2(const char*);
89
int32_t random_number();
910
void run_threads();
1011

src/myrustlib/src/hello.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std;
2-
use std::ffi::CString;
2+
use std::ffi::{CStr, CString};
33
use std::os::raw::c_char;
44

55
#[no_mangle]
@@ -9,3 +9,18 @@ pub extern fn string_from_rust() -> *const c_char {
99
std::mem::forget(s);
1010
p
1111
}
12+
13+
// Utility function to convert c_char to string
14+
fn c_char_to_string(c: *const c_char) -> String {
15+
unsafe { CStr::from_ptr(c).to_string_lossy().into_owned() }
16+
}
17+
18+
#[no_mangle]
19+
pub extern fn string_from_rust2(c_name: *const c_char) -> *const c_char {
20+
let name = c_char_to_string(c_name);
21+
22+
let s = CString::new(format!("Hello {} !", name)).unwrap();
23+
let p = s.as_ptr();
24+
std::mem::forget(s);
25+
p
26+
}

src/wrapper.c

+7
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ SEXP hello_wrapper(){
1010
return Rf_ScalarString(Rf_mkCharCE(string_from_rust(), CE_UTF8));
1111
}
1212

13+
SEXP hello_wrapper2(SEXP name){
14+
char* res = string_from_rust2(Rf_translateCharUTF8(STRING_ELT(name, 0)));
15+
return Rf_ScalarString(Rf_mkCharCE(res, CE_UTF8));
16+
}
17+
18+
1319
SEXP random_wrapper(){
1420
return Rf_ScalarInteger(random_number());
1521
}
@@ -22,6 +28,7 @@ SEXP threads_wapper(){
2228
// Standard R package stuff
2329
static const R_CallMethodDef CallEntries[] = {
2430
{"hello_wrapper", (DL_FUNC) &hello_wrapper, 0},
31+
{"hello_wrapper2", (DL_FUNC) &hello_wrapper2, 0},
2532
{"random_wrapper", (DL_FUNC) &random_wrapper, 0},
2633
{"threads_wapper", (DL_FUNC) &threads_wapper, 0},
2734
{NULL, NULL, 0}

0 commit comments

Comments
 (0)