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:

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

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

#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

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:
[1] 1 2 3

[1] 2.121996e-314

[1] 6 6 6

[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),
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.