首页 > 解决方案 > 如何使用.C接口将数组返回给R

问题描述

我有这个简单的代码:

    void test(int *testvec,  int *testlen, int *testres) {

        for (int i = 0; i < *testlen; i++){
        testres[i]=0;
        if (testvec[i] < 0){
            testres[i] = -1;}
        else if (testvec[i] == 0){
            testres[i] = 0;}
        else {testres[i] = 1;}
    }
  }
}

当我经过

testresult = function (testvec, len){
  signC = .C("signC", as.integer(testvec), as.integer(length(testvec)), as.integer(testvector("integer"), length(testvec))) 
  return (signC)
}
testvec = c(1,2,-3,0,2)

似乎什么都没有处理。我对 C 很陌生,我不明白如何在 R 中的 .C 接口的竞赛中动态地为数组赋值。

谢谢您的帮助。

标签: rc

解决方案


.C接口函数不能返回值。如果要修改 C 中的值,则需要将足够大小的向量传递给函数,并写入该向量:

sign = function (testvec) {
    sign_c = integer(length(testvec))
    .C("signC", as.integer(testvec), length(testvec), sign_c)
    sign_c
}

推荐阅读