如何 return 一个 Rcpp 列表到一个 C 函数
How to return an Rcpp List to a C function
问题
在 R 包中,我如何 return 一个 Rcpp::List
到一个 C
函数?
例子
我在 github page 上托管了一个包来说明要求。
它包含一个R
函数,它调用一个C
函数,我想调用C++
函数来检索列表。
R
#' @useDynLib crcpp c_ask_for_list
r_ask_for_list <- function() {
.Call(c_ask_for_list)
}
C
#include <Rinternals.h>
SEXP c_ask_for_list (){
SEXP l = PROTECT(allocVector(VECSXP, 1));
//l = rcpp_create_list(); // Call the C++ function to create the list
UNPROTECT(1);
return(l);
}
C++
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
extern "C" SEXP rcpp_create_list() {
Rcpp::List l(1);
l[0] = "foo";
return l;
}
如果我取消注释 C
函数中的 l = rcpp_create_list()
行,程序就会崩溃。
多亏了所有的指点,我的程序才能按预期运行。现在的完整结构是
R
#' @useDynLib crcpp c_ask_for_list
#' @export
r_ask_for_list <- function() {
.Call("c_ask_for_list", packages = "crcpp")
}
C
文件:c_ask_for_list.h
#ifndef CRCPP_H
#define CRCPP_H
#include <Rinternals.h>
#ifdef __cplusplus
extern "C" {
#endif
SEXP rcpp_create_list();
#ifdef __cplusplus
}
#endif
#endif /* CRCPP_H */
文件:c_ask_for_list.c
#include "c_ask_for_list.h"
SEXP c_ask_for_list () {
SEXP l = _crcpp_rcpp_create_list(); // Call the C++ function to create the list
return(l);
}
C++
文件:rcpp_create_list.cpp
#include <Rcpp.h>
using namespace Rcpp;
//' @importFrom Rcpp evalCpp
//' @export
// [[Rcpp::export]]
SEXP rcpp_create_list() {
Rcpp::List l(2);
l[0] = "foo";
l[1] = "bar";
return l;
}
问题
在 R 包中,我如何 return 一个 Rcpp::List
到一个 C
函数?
例子
我在 github page 上托管了一个包来说明要求。
它包含一个R
函数,它调用一个C
函数,我想调用C++
函数来检索列表。
R
#' @useDynLib crcpp c_ask_for_list
r_ask_for_list <- function() {
.Call(c_ask_for_list)
}
C
#include <Rinternals.h>
SEXP c_ask_for_list (){
SEXP l = PROTECT(allocVector(VECSXP, 1));
//l = rcpp_create_list(); // Call the C++ function to create the list
UNPROTECT(1);
return(l);
}
C++
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
extern "C" SEXP rcpp_create_list() {
Rcpp::List l(1);
l[0] = "foo";
return l;
}
如果我取消注释 C
函数中的 l = rcpp_create_list()
行,程序就会崩溃。
多亏了所有的指点,我的程序才能按预期运行。现在的完整结构是
R
#' @useDynLib crcpp c_ask_for_list
#' @export
r_ask_for_list <- function() {
.Call("c_ask_for_list", packages = "crcpp")
}
C
文件:c_ask_for_list.h
#ifndef CRCPP_H
#define CRCPP_H
#include <Rinternals.h>
#ifdef __cplusplus
extern "C" {
#endif
SEXP rcpp_create_list();
#ifdef __cplusplus
}
#endif
#endif /* CRCPP_H */
文件:c_ask_for_list.c
#include "c_ask_for_list.h"
SEXP c_ask_for_list () {
SEXP l = _crcpp_rcpp_create_list(); // Call the C++ function to create the list
return(l);
}
C++
文件:rcpp_create_list.cpp
#include <Rcpp.h>
using namespace Rcpp;
//' @importFrom Rcpp evalCpp
//' @export
// [[Rcpp::export]]
SEXP rcpp_create_list() {
Rcpp::List l(2);
l[0] = "foo";
l[1] = "bar";
return l;
}