混合 Rcpp 模块和 Rcpp::export

Bob*_*sen 4 c++ r rcpp

我想公开一个 C++ 类和一个将该类的对象作为 R 参数的函数。我必须遵循简化的示例。我创建了一个包

Rscript -e 'Rcpp::Rcpp.package.skeleton("soq")'
Run Code Online (Sandbox Code Playgroud)

并将以下代码放入 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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,最后一条注释有额外的斜线,不会导致函数被导出。当我现在运行时:

$> 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())
Run Code Online (Sandbox Code Playgroud)

一切安好。不幸的是,如果我启用Rcpp::export, docompileAttributes()并重新安装,我会得到:

** 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
Run Code Online (Sandbox Code Playgroud)

我的问题是:我如何让两者都工作?

我在 R.3.6.3 和

R> sessionInfo()
....
other attached packages:
[1] inline_0.3.15 Rcpp_1.0.4.6 
....
Run Code Online (Sandbox Code Playgroud)

附录

对于那些试图按照上面的示例进行操作的人:源文件完全命名为<package_name>_types.h. 否则,自动生成的RcppExports.cpp将不会#include,因此Echo类将不会在那里定义。这将导致编译错误。

Ral*_*ner 6

错误消息是抱怨已声明但未定义Echo(SEXP),这是为了扩展Rcpp::as<>。对于 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)
*/ 
Run Code Online (Sandbox Code Playgroud)

输出:

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

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

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

> shout(e)
Hello World!
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢,可以确认它在我的测试包中也有效! (3认同)