我正在尝试编写 C 代码以在 R 中使用,但发现 .C 函数调用不会更新输出变量。真正的 C 代码很复杂,但这里有一个简单的例子来展示行为:
void doubleMe(const int *input, int *output) {
output[0] = input[0] * 2;
}
将上述 C 函数保存到文件 doubleMe.c 中。 Linux下编译生成doubleMe.so文件:
R CMD SHLIB doubleMe.c
在 R 中,如果我执行以下操作:
dyn.load("doubleMe.so") # load it
input = 2
output = 0
.C("doubleMe", as.integer(input), as.integer(output)) # expect output=4
[[1]]
[1] 2
[[2]]
[1] 4
屏幕输出表明输入加倍,但R中的输出仍然是0:
output
[1] 0
如果我做fowllwing
output = .C("doubleMe", as.integer(input), as.integer(output))[[2]]
输出为 4。这应该适用于该示例。
但我的实际输入和输出是矩阵,我必须将输出 reshape 为正确的维度。有没有办法让.C直接调用update输出?
最佳答案
.Call()
接口(interface)使用 SEXP
数据类型,其中 P
代表指针,这是自动的:
R> Rcpp::cppFunction("void doubleMe(NumericVector x) { x = 2*x; } ")
R> x <- 1 # set to one
R> doubleMe(x) # call function we just wrote
R> x # check ...
[1] 2 # and it has doubled as a side-effect
R>
我在这里使用 Rcpp,因为它允许我在一行中执行此操作,如果您愿意,您可以在几行 C 代码中执行相同的操作。
关于c - R: 如何让.C 调用更新输出变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51603956/