0

我用 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 输出只是数据帧第一行总和的一个数字。

4

1 回答 1

1

我不知道问题是什么,但可以提供一个(有点过于雄心勃勃的)代码的工作版本。它需要你打包函数,它的工作原理是这样的:

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)
}
于 2012-06-19T09:43:20.247 回答