我用 C++ 编写了这个函数:
extern "C"
{
void add(int* first, int* second, int *n , int* sum)
{
for (int i = 0; i< *n; i++)
{
sum[i] = first[i] + second[i];
}
}
}
还有这个司机:
add <- function(twoColumn)
{
if(!is.data.frame(twoColumn))stop("twoColumn should be data.frame")
first <- twoColumn[1]
second <- twoColumn[2]
n <- length(first)
.C("add",first = as.integer(unlist(first)),second = as.integer(unlist(second)), n = as.integer(n),sum = as.integer(rep(0,n)))$sum
}
但 R 输出只是数据框第一行总和的数字。
最佳答案
我不知道问题出在哪里,但可以提供代码的(有点过于雄心勃勃的)工作版本。它需要你封装功能,并且是这样工作的:
src/add.cpp
:
SEXP add(SEXP Rx, SEXP Ry){
SEXP xy_sum;
int i;
PROTECT(xy_sum = allocVector(REALSXP, 1));
for(i = 0; i < length(Rx); i++){
REAL(xy_sum)[i] = REAL(Rx)[i] + REAL(Ry)[i];
}
UNPROTECT(1);
return xy_sum;
}
scr/add.h
:
#ifndef _add_ADD_H
#define _add_ADD_H
#include <R.h>
#include <Rdefines.h>
extern "C" SEXP add(SEXP Rx, SEXP Ry);
#endif
R/add.R
:
add <- function(x, y){
if(length(x) != length(y)) stop("Vectors must be of the same length.")
# coerce into numeric in case the user supplied something silly
.Call("add", PACKAGE="add", as.numeric(x), as.numeric(y))
}
R/zzz.R
:
.onLoad <- function(lib, pkg){
library.dynam("add", pkg, lib)
}
关于c++ - 将数组发送到 R 函数 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11096422/