gpt4 book ai didi

c - useDynLib() 错误且compileAttributes 不返回任何内容 : embedding a C library into an R package

转载 作者:行者123 更新时间:2023-11-30 14:52:50 25 4
gpt4 key购买 nike

我有一个 C 包,它构建一个带有多个参数标志的可执行文件。使用 Makefile 编译代码(我知道,这需要针对 R 包进行更改),并创建一个可执行文件以通过

运行

$ ./codeName -f path/inputfile -o path/outputfile -p ## -s "type"

我的目标是集成此 C 包中使用的多个函数,以便与 R 库一起使用。我看一下 github.com/cran 上的一些例子使用 C 的 R 包。在编写 R 扩展中,它解释了我如何使用 .Call()Makevars从 R 调用 C 函数。我想像避免瘟疫一样避免这种情况。然而,看起来这需要使用 SEXP 进行大量重写。对象——所以我转向 Rcpp(是的!)

我创建包Rcpp.package.skeleton("packageName")

太棒了。在 R 中,我执行以下操作:

$ R
> library(devtools)
> build() # works!
> install() # works!
> library(packageName)
> rcpp_hello_world()
## expected output

一切正常。然后我将我的 C 包添加到 /src 中。然后我执行Rcpp::compileAttributes()通过 R 在包根目录中——没有任何反应,也没有任何输出,这是预期的,因为我还没有更改 C 代码。

我尝试使用上面的命令进行安装:devtools::build()devtools::install() 。通过Makefile ,看起来 C 代码可以完美编译!但还有一个问题:

** R
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
Error in library.dynam(lib, package, package.lib) :
shared object ‘packageName.so’ not found
Error: loading failed
Execution halted'
ERROR: loading failed

嗯,这有点令人困惑,我不知道为什么会发生这种情况,但障碍是 useDynLib("packageName")在命名空间中。如果我删除它,C 代码似乎可以编译,并且包通过 build/install 安装。上面的命令。 rcpp_hello_world()仍然有效。

(1) 为什么会出现此错误 ‘packageName.so’ not found现在出现了,我可以绕过它吗?

(这个问题与Rcpp无关。)

然后,我转到 .c文件。我补充一下

#include <Rcpp.h>
using namespace Rcpp;

发送至 *.c文件和 //[[Rcpp::export]]在我想导入的函数之前。 (我不确定这是否适用于 *.c 或 C 头文件。)

接下来,我进入包根目录,打开 R 并尝试以下操作:

$ R
> library(Rcpp)
> compileAttributes()

运行没有错误。然而,没有RcppExports.RRcppExports.cpp被生成。编译C代码也会出现找不到#include <Rcpp.h>的错误。

(2) 为什么会 compileAttributes()在这种环境下不起作用?我一定是错误地使用了 Rcpp//[[Rcpp::export]]为了将这些 C 函数包装成 R 可用的格式。

最佳答案

你会怎么称呼这个函数? C代码?

int fib(int n) { 
if (n < 2) return n;
return fib(n-1) + fib(n-2);
}

它同时作为 C 和 C++ 代码传递。所以我们称之为 C 代码。

您可以通过 Rcpp 从 R 与以下调用者清楚地接口(interface):

// [[Rcpp::export]]
int callFib(int n) {
return fib(n);
}

将它们全部粘在一起放入一个 C++ 文件中,以便 Rcpp 可以对它们进行操作(请参阅注释),然后就完成了。

R> library(Rcpp)
R> sourceCpp("/tmp/ex.cpp")

R> callFib(10)
[1] 55
R>

完整的文件如下。

#include <Rcpp.h>

int fib(int n) {
if (n < 2) return n;
return fib(n-1) + fib(n-2);
}


// [[Rcpp::export]]
int callFib(int n) {
return fib(n);
}

/*** R
callFib(10)
*/

关于c - useDynLib() 错误且compileAttributes 不返回任何内容 : embedding a C library into an R package,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47517121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com