Rcpp:将 C 数组作为 NumericMatrix 返回给 R
Rcpp: Returning C array as NumericMatrix to R
#include <Rcpp.h>
#include <vector>
extern "C"
{
#include "cheader.h"
}
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector cppfunction(NumericVector inputR){
double const* input = inputR.begin();
size_t N = inputR.size();
double output[10*N];
cfunction(input, N, output);
std::vector<double> outputR(output, output + sizeof(output) / sizeof(double));
return wrap(outputR);
}
这有效,除了我必须手动将矢量输出 R 转换为 R 中的矩阵。我当然也可以将输出R转换为NumericMatrix(或者我可以吗?(,然后返回它,但我真正的问题是上述过程是最佳的吗?我是否必须首先将输出转换为 std::vector,然后转换为 NumericVector/Matrix,或者我可以以某种方式避免这种情况吗?我尝试直接包装输出,但这不起作用。
把它放在一个文件中,cppfunction.cpp
,然后通过 library(Rcpp); sourceCpp("cppfunction.cpp")
运行它。 由于没有提供cfunction
,我们提供了一个为每个输入元素加 1 的元素:
#include <Rcpp.h>
using namespace Rcpp;
void cfunction(double* x, int n, double* y) {
for(int i = 0; i < n; i++) y[i] = x[i] + 1;
}
// [[Rcpp::export]]
NumericVector cppfunction(NumericVector x){
NumericVector y(x.size());
cfunction(REAL(x), x.size(), REAL(y));
return y;
}
/*** R
x <- c(1, 2, 3, 4)
cppfunction(x)
## [1] 2 3 4 5
*/
如果要返回NumericMatrix
则假设x
的长度具有整数平方根:
#include <Rcpp.h>
using namespace Rcpp;
void cfunction(double* x, int n, double* y) {
for(int i = 0; i < n; i++) y[i] = x[i] + 1;
}
// [[Rcpp::export]]
NumericMatrix cppfunctionM(NumericVector x){
int n = sqrt(x.size());
NumericMatrix y(n, n);
cfunction(REAL(x), x.size(), REAL(y));
return y;
}
/*** R
x <- c(1, 2, 3, 4)
cppfunctionM(x)
## [,1] [,2]
## [1,] 2 4
## [2,] 3 5
*/
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- Rcpp:将 C 数组作为 NumericMatrix 返回给 R