r - 从 R 调用 Rcpp 文件时加载错误,然后在其中回调

标签 r rcpp argv rinside

我编写了一个R程序,它调用 hello1() ,这是 demo2.cpp 中包含的 Rcpp 函数程序

library(Rcpp)
ssss <- function(dd)
{
    return(paste("hello ",dd))
}

sourceCpp(file='demo2.cpp')
currentpath <- "/home/xuyan/R/parallel/"
aaa <-hello1(0,currentpath)
print(aaa)

我的demo2.cpp是:

#include <Rcpp.h>
#include <string>
#include <RInside.h>

using namespace std;
using namespace Rcpp;

// [[Rcpp::export]]
int  hello1(int argc,string path)
{
    const char *argv[] = {path.c_str()};
    RInside R(argc,argv);
    R["txt"] = "Hello, world!\n";     

    R["sourcer"] = "demo.r";
    R.parseEvalQ("source(sourcer)");
    string str = Rcpp::as<string>(R.parseEval("ssss(txt)"));
    cout << "result is" << str << endl;
    return(111);
}

我尝试使用以下命令启动此脚本:

Rscript demo.r

我收到以下错误:

Error in dyn.load("/tmp/RtmpZl0JKp/sourceCpp-x86_64-pc-linux-gnu-0.12.10/sourcecpp_90cc33eafd15/sourceCpp_2.so") : unable to load shared object '/tmp/RtmpZl0JKp/sourceCpp-x86_64-pc-linux-gnu-0.12.10/sourcecpp_90cc33eafd15/sourceCpp_2.so': /tmp/RtmpZl0JKp/sourceCpp-x86_64-pc-linux-gnu-0.12.10/sourcecpp_90cc33eafd15/sourceCpp_2.so: undefined symbol: _ZN7RInsideD1Ev Calls: sourceCpp -> source -> withVisible -> eval -> eval -> dyn.load Execution halted

事实上,我想解决Rfor 的缓慢问题环形。我有一个R程序,它有一个大的 for循环并且执行速度非常慢。所以,我想改变forR循环到C++代码。 for内循环中,我调用了许多R函数。因此,我需要从C++代码调用R程序。因此,顺序是RC++R,即RRcpp> 致Rinside,我错了吗?

为什么?

最佳答案

鉴于您已经有一个事件的 R session ,您不应该在 C++ 中创建新的 R session 。话虽如此,不要同时包含 Rcpp.hRInside.h。在这种情况下,您应该只使用 Rcpp.h

所以,只需使用:

#include <Rcpp.h>

// [[Rcpp::export]]
int  hello1(int argc, string path)
{
    const char *argv[] = {path.c_str()};
    return(111);
}

编辑 1

根据后来删除的评论,我认为您想在 C++ 中使用一些 R 函数。为此,请使用 RcppFunction 类。确保首先通过运行声明将R函数加载到内存中。完成此操作后,编译以下C++代码:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::CharacterVector hello1()
{
    Rcpp::Function some_r_func("ssss");

    return some_r_func("a");
}

最终编辑

In fact, I want to solve slowness of R's for loop. I have an R program that has a large for loop and it execute very slowly. So, I want to change that for loop from R to C++ code. Within the for loop, I call many R functions. So, I need to call from C++ code to R program. Thus, the order is R to C++ to R, that is R to Rcpp to Rinside, am I wrong?

仅将调用 R 函数的循环从 R 切换到 C++ 并期望加速是不正确的。然后,每次遇到 R 函数时,同一个循环都必须伸出援手,并与 R session 进行通信。本质上,它有效地暂停了C++代码,等待R代码执行并产生结果,然后恢复C++ shell。

在此范式中有效加速代码的唯一方法是用C++完全编写所有R函数,然后调用它们的C++ for 循环中的 C++ 等效项。

请参阅我之前对“R to Rcpp to Rinside”的评论,这又是一个NO。永远不要这样做。时期。只有“R 到 Rcpp”或“C++ 到 RInside”是可行的。

关于r - 从 R 调用 Rcpp 文件时加载错误,然后在其中回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43220503/

相关文章:

r - 在 Rcpp 中创建 R S4 类的对象?

c++ - 可以在运行时更改 argv(不是由应用程序本身)

c - 在 C 程序中使用 arg[v] 命令行参数

R 如何从数据框中的长列名中删除字符

r - 检查每个具有相同唯一 ID 的唯一值

r - 在多面图中用 N 注释 x 轴

r - 如何计算R中多列的出现次数

c++ - 重复 Rcpp NumericVector

c++ - 用于填充单位法线的 RcppEigen 模板函数

c - 将 argv[1] 保存到 char* 变量会在传递给单独的函数时导致段错误