Can RStudio communicate with C++ executive file through dyn.load?

I got very strange results when using RStudio to call C++. Here is my R code:

dyn.load("toy.so")
a1<- c(1.0,2.0, 3.0)
a2<- 2.5
y<- rep(6, length(a1))
ans1<- .C("try1", a1=as.numeric(a1),
a2=as.numeric(a2),
y=as.integer(y),
size=as.integer(length(a1)) )
ans1

I want to return a vector y=1*(a1>a2) from my C++ code below

#include
#include <stdio.h>
#include <float.h>
using namespace std;
extern "C"{
void hv1(double a1, double a2, int y, int* size) {
for (int i=0; i< size; i++){
y[i] = 1
(a1[i]>a2);
}
return;
}}

I used terminal command
R CMD SHLIB toy.cpp
to compile C++ without error. However, when I run the above R code, RStudio gives me the following strange return in ans1$a2 and ans1$y:
$a1
[1] 1 2 3

$a2
[1] 2.121996e-314

$y
[1] 6 6 6

$size
[1] 3

When I run the same R code trice, the RStudio says there is a fatal error in R and closes my RStudio. I tried to use Window PC and created a toy.dll file and dyn.load("toy.dll") with the same error. Can someone help me figure out the problem for me? It seem the problem is not from C++ but is from RStudio. Thanks.

In the R code, I used function "hv1", not "try1". I forgot to change it when I posted the problem. The problem remains when using "hv1":

ans1<- .C("hv1", a1=as.numeric(a1),
a2=as.numeric(a2),
y=as.integer(y),
size=as.integer(length(a1)) )

Have you considered using Rcpp?

I chose to use c++ instead of Rcpp since c++ is more flexible in some features that Rcpp does not provide.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.