简体   繁体   English

Rcpp C / C ++使用结构和字符*

[英]Rcpp C/C++ using structs and char*

Newbie to C/C++ and Rcpp. 新手到C / C ++和Rcpp。

I'm currently trying to modify examples I find (in this case I modified the "yada" module example http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-modules.pdf ) and extend them to test my understanding. 我正在尝试修改我找到的示例(在本例中我修改了“yada”模块示例http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-modules.pdf )并扩展他们来测试我的理解。

The example I have currently compiles but, does not have the expected behaviour. 我目前编译的示例,但没有预期的行为。 My guess it that I'm missing something, but I can't determine what is missing from I find in the docs. 我猜它我错过了一些东西,但我无法确定我在文档中发现的缺失。 Any help would be much appreciated. 任何帮助将非常感激。

the example code is below. 示例代码如下。

library(inline)
fx=cxxfunction(,plugin="Rcpp",include='#include<Rcpp.h>
#include<string>

typedef struct containerForChars {const char *b;} containChar;

containChar cC;

const char* toConstChar(std::string s){return s.c_str();}

void setB(std::string s){
    cC.b = toConstChar(s);
}

std::string getB(void){
    std::string cs = cC.b;
    return cs;
}
RCPP_MODULE(ex1){
  using namespace Rcpp;
  function("setB",&getB);
  function("getB",&getB);
}')
mod=Module("ex1",getDynLib(fx))
f<-mod$setB
g<-mod$getB
f("asdf")
g()

Instead of f("asdf") setting cC.b to "asdf" , I get the following error, 而不是f("asdf")cC.b设置为"asdf" ,我得到以下错误,

Error in f("asdf") : unused argument ("asdf")

My hope is that the arg to f() will be set as the value for cC.b , and g() will retrieve or get the value I set with f . 我希望将f()的arg设置为cC.b的值, g()将检索或获取我用f设置的值。 My guess is that whatever magic that Module and RCPP_MODULE do isn't capable of using the struct I defined. 我的猜测是,Module和RCPP_MODULE所做的任何魔法都不能使用我定义的结构。 I guess hoping for it to work wasn't enough :P. 我想希望它的工作还不够:P。

Common typo. 常见错字。 Instead of 代替

 function("setB",&getB);
 function("getB",&getB);

do

 function("setB",&setB);     # set, not get
 function("getB",&getB);

and then everything works: 一切正常:

R> f("asdf")    
R> g()          
[1] "asdf" 
R>   

I'd also add library(inline) at the top. 我还在顶部添加library(inline)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM