We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a42346c commit e278d15Copy full SHA for e278d15
R/hello.R
@@ -18,6 +18,14 @@ hello2 <- function(name) {
18
.Call(hello_wrapper2, name)
19
}
20
21
+#' @export
22
+#' @rdname hellorust
23
+#' @examples rev()
24
+#' @useDynLib hellorust rev_wrapper
25
+rev <- function(x) {
26
+ .Call(rev_wrapper, x)
27
+}
28
+
29
#' @export
30
#' @rdname hellorust
31
#' @examples random()
src/myrustlib/api.h
@@ -4,8 +4,16 @@
4
extern "C" {
5
#endif
6
7
+// A struct to pass the results from Rust to C
8
+typedef struct
9
+{
10
+ double *data;
11
+ uint32_t len;
12
+} Slice;
13
14
char * string_from_rust();
15
char * string_from_rust2(const char*);
16
+Slice rev_slice(Slice);
17
int32_t random_number();
void run_threads();
src/myrustlib/src/lib.rs
@@ -6,8 +6,12 @@ extern crate rand;
mod hello;
mod random;
mod mythreads;
+mod slice;
// Export functions called by R
pub use hello::string_from_rust;
+pub use hello::string_from_rust2;
pub use random::random_number;
pub use mythreads::run_threads;
+pub use slice::rev_slice;
+pub use slice::Slice;
src/myrustlib/src/slice.rs
@@ -0,0 +1,26 @@
1
+use std;
2
+use std::os::raw::{c_double, c_uint};
3
+#[repr(C)]
+pub struct Slice {
+ data: *mut c_double,
+ len: c_uint,
+#[no_mangle]
+pub extern fn rev_slice(s: Slice) -> Slice {
+ // convert from Slice to Rust slice
+ let s = unsafe { std::slice::from_raw_parts_mut(s.data, s.len as _) };
+ let mut v = s.to_vec();
+ v.reverse();
+ let len = v.len();
+ let v_ptr = v.as_mut_ptr();
+ std::mem::forget(v);
+ Slice {
+ data: v_ptr,
+ len: len as _,
+ }
src/wrapper.c
@@ -15,6 +15,19 @@ SEXP hello_wrapper2(SEXP name){
return Rf_ScalarString(Rf_mkCharCE(res, CE_UTF8));
+SEXP rev_wrapper(SEXP x){
+ Slice s = {REAL(x), Rf_length(x)};
+ Slice s_rev = rev_slice(s);
+ SEXP out = PROTECT(Rf_allocVector(REALSXP, s_rev.len));
+ for (int i = 0; i < s_rev.len; i++) {
+ SET_REAL_ELT(out, i, s_rev.data[i]);
+ UNPROTECT(1);
+ return out;
32
SEXP random_wrapper(){
33
return Rf_ScalarInteger(random_number());
@@ -29,6 +42,7 @@ SEXP threads_wapper(){
42
static const R_CallMethodDef CallEntries[] = {
43
{"hello_wrapper", (DL_FUNC) &hello_wrapper, 0},
44
{"hello_wrapper2", (DL_FUNC) &hello_wrapper2, 0},
45
+ {"rev_wrapper", (DL_FUNC) &rev_wrapper, 0},
46
{"random_wrapper", (DL_FUNC) &random_wrapper, 0},
47
{"threads_wapper", (DL_FUNC) &threads_wapper, 0},
34
48
{NULL, NULL, 0}
0 commit comments