[英]Error calling C++ function from R - library loads, but function is not on the table
Here is the C code: 这是C代码:
// a.cpp
void double_me(int* x) {
// takes a numeric input and doubles it
*x = *x + *x;
}
I compile the code with 我用编译代码
>R CMD SHLIB a.cpp
After that i run R and type following commands: 之后,我运行R并键入以下命令:
dinfo <- dyn.load("a.so")
.C("double_me",x=2)
This end with error: "double_me" is not on the list. 结束于错误:“ double_me”不在列表中。
Now the question: dyn.load works fine, dinfo contains: 现在的问题是:dyn.load可以正常工作,dinfo包含:
DLL name: a Filename: /Users/myusername/a.so Dynamic lookup: TRUE
DLL名称:文件名:/Users/myusername/a.so动态查找:TRUE
But the function is not on the table: 但是函数不在表中:
is.loaded("double_me") [1] FALSE
is.loaded(“ double_me”)[1]否
How could it happen? 怎么会这样 This happens on macOS.
这是在macOS上发生的。
This is because you are using a.cpp
; 这是因为您正在使用
a.cpp
; C++ function names are "mangled" by the compiler. C ++函数名称被编译器“破坏”。 You can use your same code with the filename
ac
, compiling it just as you did, and get the following from R: 您可以将相同的代码与文件名
ac
,像以前一样对其进行编译,然后从R中获取以下内容:
> dinfo <- dyn.load("a.so")
> .C("double_me",x=2)
$x
[1] 2
Or, alternatively, you can add this line to the top of a.cpp
: 或者,您也可以将此行添加到
a.cpp
的顶部:
extern "C" void double_me(int* x);
and get the following from R: 并从R中获得以下内容:
> dinfo <- dyn.load("a.so")
> .C("double_me",x=2)
$x
[1] 2
If you do not coerce the argument to the proper type, a copy may be made, such that your original value is not altered; 如果不将参数强制转换为正确的类型,则可能会进行复制,以使您的原始值不变。 if we coerce the value to be an integer as we should when using
.C()
, we get the expected result: 如果使用
.C()
强制将值强制为整数,则将得到预期的结果:
> dyn.load("a.so")
> .C("double_me", x = as.integer(2))
$x
[1] 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.