2013-10-14 20 views
2

C/C++和Rcpp的新手。使用結構和字符的Rcpp C/C++ *

我目前正在嘗試修改我發現的示例(在這種情況下,我修改了「yada」模塊示例http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-modules.pdf)並將其擴展以測試我的理解。

我目前編譯的例子,但沒有預期的行爲。我的猜測是我錯過了一些東西,但我無法確定在文檔中找不到什麼。任何幫助將非常感激。

示例代碼如下。

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() 

而不是f("asdf")設置cC.b"asdf",我得到以下錯誤,

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

我的希望是,對Arg的f()將被設置爲cC.b值,g()將檢索或獲得我用f設定的值。我的猜測是,無論模塊和RCPP_MODULE做什麼魔術都不能使用我定義的結構。我想希望它能夠工作還不夠:P。

+0

「但是,沒有預期的行爲。」爲了能夠幫助你,你必須啓發我們,瞭解你期望的行爲? – codeling

+0

在底部編輯了一些問題的動機。 – csta

回答

3

常見的錯字。取而代之的

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

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

,然後一切正常:

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

我還會在頂部加入library(inline)

+0

Arg ...謝謝。 – csta