[英]R Package: Call C Function Within Rcpp
我正在寫一個包含C和Rcpp的R包。 目標是從R和Rcpp中調用C函數,最終在Rcpp中執行大部分分析,並且僅返回R以執行最少的任務。 我的包編譯並從R調用我的函數工作正常。
#generate some matrix. Numeric is fine too. Must have column names, no row names
myMat <- matrix(data = 1:100, nrow = 10, ncol = 10,
dimnames = list(NULL, LETTERS[1:10]))
#This works. Put in full path, no expansion. It returns null to the console.
MinimalExample::WriteMat(mat = myMat, file = "Full_Path_Please/IWork.csv",
sep = "," ,eol = "\n", dec = ".", buffMB = 8L)
但是,在Rcpp中嘗試相同的操作會產生SIGSEV錯誤。 我認為問題是我如何將參數傳遞給函數,但我無法弄清楚正確的方法。
#include <Rcpp.h>
using namespace Rcpp;
extern "C"{
#include "fwrite.h"
}
//' @export
// [[Rcpp::export]]
void WriteMatCpp(String& fileName, NumericMatrix& testMat){
Rcpp::Rcout<<"I did start!"<<std::endl;
String patchName = fileName;
int whichRow = 1;
std::string newString = std::string(3 - toString(whichRow).length(), '0')
+ toString(whichRow);
patchName.replace_last(".csv", newString+".csv");
//Set objects to pass to print function
String comma = ",";
String eol = "\n";
String dot = ".";
int buffMem = 8;
//This is where I crash, giving a SIGSEV error
fwriteMain(testMat, (SEXP)&patchName, (SEXP)&comma, (SEXP)&eol,
(SEXP)&dot, (SEXP)&buffMem);
}
這是包含GitHub存儲庫的鏈接。 https://github.com/GilChrist19/MinimalExample
你從C ++到C的調用是錯誤的。 你不能只是在任意數據結構前寫(SEXP)&
並希望它成為一個SEXP
。
使用這樣的SEXP
C ++中的內容SEXP
C函數在每個參數上使用Rcpp::wrap()
期望的Rcpp::wrap()
:
//This is where I crash, giving a SIGSEV error
fwriteMain(wrap(testMat), wrap(patchName), wrap(comma),
wrap(eol), wrap(dot), wrap(buffMem));
edd@brad:/tmp/MinimalExample/MinEx(master)$ Rscript RunMe.R
I did start!
edd@brad:/tmp/MinimalExample/MinEx(master)$ cat /tmp/IDoNotWork.csv
A,B,C,D,E,F,G,H,I,J
1,11,21,31,41,51,61,71,81,91
2,12,22,32,42,52,62,72,82,92
3,13,23,33,43,53,63,73,83,93
4,14,24,34,44,54,64,74,84,94
5,15,25,35,45,55,65,75,85,95
6,16,26,36,46,56,66,76,86,96
7,17,27,37,47,57,67,77,87,97
8,18,28,38,48,58,68,78,88,98
9,19,29,39,49,59,69,79,89,99
10,20,30,40,50,60,70,80,90,100
edd@brad:/tmp/MinimalExample/MinEx(master)$
有關完整示例,請參閱https://github.com/GilChrist19/MinimalExample/tree/master/MinEx 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.