File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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()
Original file line number Diff line number Diff line change @@ -5,6 +5,7 @@ extern "C" {
55#endif
66
77char * string_from_rust ();
8+ char * string_from_rust2 (const char * );
89int32_t random_number ();
910void run_threads ();
1011
Original file line number Diff line number Diff line change 11use std;
2- use std:: ffi:: CString ;
2+ use std:: ffi:: { CStr , CString } ;
33use 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+ }
Original file line number Diff line number Diff 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+
1319SEXP random_wrapper (){
1420 return Rf_ScalarInteger (random_number ());
1521}
@@ -22,6 +28,7 @@ SEXP threads_wapper(){
2228// Standard R package stuff
2329static 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 }
You can’t perform that action at this time.
0 commit comments