在 运行 时间(即时)编译 C++ 代码的 R 包

R package that compile C++ code at run-time (on the fly)

我正在编写一个应该能够即时编译 C++ 代码的 R 包。在实践中,用户可以在 运行 时定义基于 C++ 代码的运算符,这些运算符被编译然后用于计算(出于效率目的,如 Python 中的 PyTorch 或 TensorFlow 模型)。理想情况下,在 运行 时编译的代码应该使用 Rcpp 特性导出到 R。

示例:

  1. 在我的 R 包中,我有一个函数 def_operator 可以解析一些定义运算符的数学公式。
my_custom_op <- def_operator("x+y", args = c("x", "y"))
  1. 我的 Cpp API 知道如何生成与此公式关联的 Cpp 代码。这段代码应该即时编译(只编译一次,而不是每次调用时)。

  2. 用户可以使用这个新函数进行一些计算。

res <- my_custom_op(1, 3) # should give 4

注意:这是一个例子,用户定义的运算符目的是为了做更多的标量相加,兴趣显然是让用户定义它的运算符和不要预先定义一些在安装时编译的通用运算符。

我暂时知道两件事:

这是我的问题:

  • Do you know some alternative to sourceCpp from the Rcpp package to compile C++ code on the fly and export it to R?

使用 sourceCpp()最好的 方法。或者,您可以使用 inline R 包中的前身。否则,您将需要通过 R CMD SHLIB 构建自己的文件、加载库并自行创建包装器。 (不好玩。)

  • Is there some way to manage compilation option for sourceCpp other than using the file ~/.R/Makevars (I need to link the code in the inst directory and I don't want to edit this file on the user system)?

是的,每个 R 会话可以通过 Sys.setenv("PKG_LIBS" = ...).

设置许多 Makevars 变量

现在,要动态检索文件位置,请考虑 RcppMLPACK1 的标志函数方法。

  • Eventually, do you know some R packages implementing compilation on the fly that I could take as examples?

这个市场有几个进入者:

  • armacmp package by Dirk Schumacher that translates R code to C++ under the armadillo图书馆。
  • nCompiler 由 Perry de Valpine 等人提供的软件包。用于代码生成 C++ 并轻松连接 R 和 C++。