gpt4 book ai didi

r - 将 char* 转换为 SEXP

转载 作者:行者123 更新时间:2023-12-04 11:32:09 25 4
gpt4 key购买 nike

我需要将已知长度的 const char* 转换为 Rcpp::RawVector 以返回到 R.

Rcpp::wrap 适用于许多类型,但似乎不适用于 char *

最佳答案

library(Rcpp)
library(inline)

ƒ <- rcpp(body='
const char* text = "this is some text";
Rcpp::RawVector rv(strlen(text));
for(unsigned int i=0; i<strlen(text); i++) { rv[i] = text[i]; }
return(rv);
')

ƒ()
## [1] 74 68 69 73 20 69 73 20 73 6f 6d 65 20 74 65 78 74

rawToChar(ƒ())
## [1] "this is some text"

更新

@nrussellmethod更好:

#include <Rcpp.h>
#include <cstring>

// [[Rcpp::export]]
Rcpp::RawVector to_raw(const char* str) {
Rcpp::RawVector res(str, str + std::strlen(str));
return res;
}

关于r - 将 char* 转换为 SEXP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39250448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com