混合Rcpp模块和Rcpp :: export

问题描述 投票:1回答:1

我想公开一个C ++类和一个将该类的对象作为R的参数的函数。我必须遵循以下简化示例。我使用

创建了一个包
Rscript -e 'Rcpp::Rcpp.package.skeleton("soq")'

并将以下代码放入soq_types.h

#include <RcppCommon.h>
#include <string>

class Echo {
  private:
  std::string message;
  public:
  Echo(std::string message) : message(message) {}
  Echo(SEXP);

  std::string get() { return message; }
};

#include <Rcpp.h>

using namespace Rcpp;

RCPP_MODULE(echo_module) {
  class_<Echo>("Echo")
  .constructor<std::string>()
  .method("get", &Echo::get)
  ;
};

//// [[Rcpp::export]]
void shout(Echo e) {
  Rcout << e.get() << "!" << std::endl;
}

请注意,最后一条注释带有多余的斜杠,并且不会导致函数导出。当我现在运行时:

$> Rscript -e 'Rcpp::compileAttributes()'
$> R CMD INSTALL .

R> library(Rcpp)
R> suppressMessages(library(inline))
R> library(soq)
R> echo_module <- Module("echo_module", getDynLib("soq"))
R> Echo <- echo_module$Echo
R> e <- new(Echo, "Hello World")
R> print(e$get())

一切都很好。不幸的是,如果启用Rcpp::export,请执行compileAttributes()并重新安装,我会得到:

** testing if installed package can be loaded from temporary location
Error: package or namespace load failed for ‘soq’ in dyn.load(file, DLLpath = DLLpath, ...):
 unable to load shared object '/home/brj/R/x86_64-pc-linux-gnu-library/3.6/00LOCK-soq/00new/soq/libs/soq.so':
  /home/brj/R/x86_64-pc-linux-gnu-library/3.6/00LOCK-soq/00new/soq/libs/soq.so: undefined symbol: _ZN4EchoC1EP7SEXPREC
Error: loading failed
Execution halted
ERROR: loading failed

我的问题是:我该如何同时工作?

我正在使用R.3.6.3和

R> sessionInfo()
....
other attached packages:
[1] inline_0.3.15 Rcpp_1.0.4.6 
....
c++ r rcpp
1个回答
0
投票

错误消息抱怨已声明但未定义的Echo(SEXP)。对于由Rcpp模块处理的类,使用RCPP_EXPOSED_*宏更加容易:

 #include <Rcpp.h>

class Echo {
private:
    std::string message;
public:
    Echo(std::string message) : message(message) {}

    std::string get() { return message; }
};

RCPP_EXPOSED_AS(Echo);

using namespace Rcpp;

RCPP_MODULE(echo_module) {
    class_<Echo>("Echo")
    .constructor<std::string>()
    .method("get", &Echo::get)
    ;
};

// [[Rcpp::export]]
void shout(Echo e) {
    Rcout << e.get() << "!" << std::endl;
}

/***R
e <- new(Echo, "Hello World")
print(e$get())
shout(e)
*/ 

输出:

> Rcpp::sourceCpp('62228538.cpp')

> e <- new(Echo, "Hello World")

> print(e$get())
[1] "Hello World"

> shout(e)
Hello World!

所有这些都不在包装内,而是使用Rcpp::sourceCpp。我希望它也可以在一个包中工作。

© www.soinside.com 2019 - 2024. All rights reserved.