【问题标题】:Load error calling Rcpp file from R then call back in it从 R 调用 Rcpp 文件时加载错误,然后在其中回调
【发布时间】:2017-04-05 01:51:38
【问题描述】:

我写了一个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

我收到以下错误:

错误 dyn.load("/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': /tmp/RtmpZl0JKp/sourceCpp-x86_64-pc-linux-gnu-0.12.10/sourcecpp_90cc33eafd15/sourceCpp_2.so: 未定义符号:_ZN7RInsideD1Ev 调用:sourceCpp -> source -> withVisible -> eval -> eval -> dyn.load 执行停止

其实我是想解决Rfor循环慢的问题。我有一个 R 程序,它有一个大的 for 循环,它执行非常缓慢。因此,我想将 for 循环从 R 更改为 C++ 代码。在for 循环中,我调用了许多R 函数。所以,我需要从 C++ 代码调用 R 程序。因此,顺序是R to C++ to R,即R to RcppRinside,我错了吗?

为什么?

【问题讨论】:

    标签: r rcpp argv rinside


    【解决方案1】:

    您应该在 C++ 中创建一个新的 R 会话,因为您已经有一个活动的 R 会话。话虽如此,NOT 包括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");
    }
    

    最终编辑

    事实上,我想解决 R 的 for 循环缓慢的问题。我有一个 R 程序,它有一个大的 for 循环,它执行得非常慢。因此,我想将 for 循环从 R 代码更改为 C++ 代码。在 for 循环中,我调用了许多 R 函数。所以,我需要从 C++ 代码调用 R 程序。因此,顺序是 R 到 C++ 到 R,即 R 到 Rcpp 到 Rinside,我错了吗?

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

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

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

    【讨论】:

    • 如果我能投票十多次,我会的,保证!
    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    相关资源
    最近更新 更多