I'm trying to reproduce an R example based in R help.
This is an example for cxxfunction from inline package.
require(Rcpp)
require(inline)
# Rcpp plugin
if( require( Rcpp ) ){
fx <- cxxfunction( signature(x = "integer", y = "numeric" ) , '
return wrap( as<int>(x) * as<double>(y) ) ;
', plugin = "Rcpp" )
fx( 2L, 5 )
## equivalent shorter form using rcpp()
fx <- rcpp(signature(x = "integer", y = "numeric"),
' return wrap( as<int>(x) * as<double>(y) ) ; ')
}
I got this message:
Error in compileCode(f, code, language = language, verbose = verbose) :
Compilation ERROR, function(s)/method(s) not created! Warning message:
running command 'make -f "C:/PROGRA~1/R/R-30~1.3/etc/i386/Makeconf" -f "C:/PROGRA~1/R/R-30~1.3/share/make/winshlib.mk" ....
And in addition:
Warning message:
running command 'C:/PROGRA~1/R/R-30~1.3/bin/i386/R CMD SHLIB file3a86e316ef8.cpp ...
I'm using:
platform i386-w64-mingw32 and R-3.0.3
As Kevin said, its easier to use attributes. The attribute // [[Rcpp::export]] does all the work for you.
With the current versions on R and Rcpp installed create a file called test.cpp to put this code:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double fx(int x, double y){
return x*y;
}
/*** R
fx(2L,5)
fx(2L,5.1)
*/
Then in a R session run: Rcpp::sourceCpp('test.cpp')
That should work, if you have followed the instructions for installing R, R-tools and set PATH variables (if on windows) correctly.
Related
I am trying to use these codes :
R:
library(Rcpp)
library(inline)
myplugin <- getPlugin("Rcpp")
myplugin$env$PKG_CXXFLAGS<-"-lsequence -lz"
cppFile2<-"Codes.cpp"
path<-"/home/samman/Documents/publishing/popstructMeta/LibseqR/"
sourceCpp(paste(path,cppFile2,sep=""))
basic_function()
C++
#include <Rcpp.h>
#include <Sequence/Translate.hpp>
// [[Rcpp::export]]
Rcpp::StringVector basic_function( ) {
std::string codon;
codon.resize(3);
// add code here
codon[0] = 'A';
codon[1] = 'G';
codon[2] = 'C';
Sequence::Translate(codon.begin(),codon.end());
return Rcpp::StringVector::create( "foo", "bar" ) ;
}
The same code is running very good in g++ after adding to the .bashrc file "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib".
The R code gives me this error :
Error in dyn.load("/tmp/RtmpJZm4Sc/sourceCpp-x86_64-pc-linux-gnu-1.0.10/sourcecpp_1257a68dd7ef5/sourceCpp_2.so") :
unable to load shared object '/tmp/RtmpJZm4Sc/sourceCpp-x86_64-pc-linux-gnu-1.0.10/sourcecpp_1257a68dd7ef5/sourceCpp_2.so':
/tmp/RtmpJZm4Sc/sourceCpp-x86_64-pc-linux-gnu-1.0.10/sourcecpp_1257a68dd7ef5/sourceCpp_2.so: undefined symbol: _ZN8Sequence9TranslateEN9__gnu_cxx17__normal_iteratorIPKcNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEESA_NS_12GeneticCodesERS2_
Calls: sourceCpp -> source -> withVisible -> eval -> eval -> dyn.load
I am working with R and C++. I am trying to include C++ in R , I have the following code:
install.packages('inline')
install.packages('Rcpp')
install.packages('rstan')
library('inline')
library('Rcpp')
library('rstan')
### # start with pure C/C++ function and assign the source code to
### # a variable which we call here includesrc
includesrc <- '
int fibonacci(const int x){
if (x == 0) return(0);
if (x == 1) return(1);
return fibonacci(x-1) + fibonacci(x-2);
}'
### # define the body of the C/C++ program
fibCppBody <- '
int x = Rcpp::as<int>(xs);
return Rcpp::wrap( fibonacci(x) );'
### # pass the above C/C++ function as an argument
### # to cxxfunction()
fibRcpp <- inline::cxxfunction(sig = signature(xs = "int"),
plugin = "Rcpp",
incl = includesrc,
body = fibCppBody)
sapply(1:10, fibRcpp, USE.NAMES = FALSE)
I ran this code which is supposed to include C++ code in R function , it is supposed to run (it is an example from here but it's not working for me.
And I got this error:
Compilation ERROR, function(s)/method(s) not created!
Error in compileCode(f, code, language = language, verbose = verbose) :
Warning message:In system(cmd) : 'make' not found
Any idea? Thanks
I built my own function and everythings goes well unless for .c files.
My package has src folder to save my foo.c files in it.
void foo(double *x, int *length) {
for(int i=0; i<*length; i++) {
x[i] = x[i]+1;
}
}
I saved this simple foo.c file in src and build my package using build tap in Rstudio. Then I saved the wrapper R funciton inside R folder of the package.
addone <- function(x) {
x <- as.double(x)
.C("foo", DUP=F, x, length(x))
return(x)
}
Then I got this error.
Error in .C("foo", DUP = F, x, length(x)) :
C symbol name "foo" not in load table
I am a mac user.
Any help please?
I am having some trouble working through the examples inside:
http://dirk.eddelbuettel.com/code/rcpp/Rcpp-modules.pdf
Specifically, section 2.2 where the author goes to expose a C++ class in RCPP and making it available to call in R.
I copied the code in to a new RCPP file and sourced it with no problem but got an error when I ran the following in R:
require(Rcpp)
require(inline)
unif_module <- Module( "unif_module", getDynLib(fx_unif ) )
The error:
Error in getDynLib(fx_unif) :
error in evaluating the argument 'x' in selecting a method for function 'getDynLib': Error: object 'fx_unif' not found
I then went though the other parts of the document where getDynLib is used and found that none of them initialized the arguments passed in to getDynLib. My question is what is fx_unif?
Thanks,
Update:
So following another example within the paper i tried:
inc = '
class Uniform {
public:
Uniform(double min_, double max_) : min(min_), max(max_) {}
NumericVector draw(int n) const {
RNGScope scope;
return runif( n, min, max );
}
double min, max;
};
double uniformRange( Uniform* w) {
return w->max - w->min;
}
RCPP_MODULE(unif_module) {
class_<Uniform>( "Uniform" )
.constructor<double,double>()
.field( "min", &Uniform::min )
.field( "max", &Uniform::max )
.method( "draw", &Uniform::draw )
.method( "range", &uniformRange )
;
}
'
fx_unif = cxxfunction(signature(), plugin="Rcpp", include=inc)
error:
Error in compileCode(f, code, language = language, verbose = verbose) :
Compilation ERROR, function(s)/method(s) not created! Warning message:
running command 'make -f "C:/PROGRA~1/R/R-32~1.2/etc/x64/Makeconf" -f "C:/PROGRA~1/R/R-32~1.2/share/make/winshlib.mk" SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)' SHLIB="filef4028245a6f.dll" WIN=64 TCLBIN=64 OBJECTS="filef4028245a6f.o"' had status 127
In addition: Warning message:
running command 'C:/PROGRA~1/R/R-32~1.2/bin/x64/R CMD SHLIB filef4028245a6f.cpp 2> filef4028245a6f.cpp.err.txt' had status 1
I have the following code in my project:
class RangeConverter {
private:
struct Converter {
double MinimumInput;
double MaximumInput;
double MinimumOutput;
double MaximumOutput;
template <typename RangeType>
RangeType Convert ( RangeType invalue ) const {
double v = static_cast<double> ( invalue );
if ( v < MinimumInput ) {
v = MinimumInput;
} else if ( v > MaximumInput ) {
v = MaximumInput;
}
double interpolationfactor = ( v - MinimumInput ) / ( MaximumInput - MinimumInput );
return static_cast<RangeType> ( ( interpolationfactor * ( MaximumOutput - MinimumOutput ) ) + MinimumOutput );
}
};
.....
After formatting that code with AStyle I get the following:
class RangeConverter {
private:
struct Converter {
ngeConverter {
private:
struct Converter {
double MinimumInput;
double MaximumInput;
double MinimumOutput;
double MaximumOutput;
template <typename RangeType>
RangeType Convert ( RangeType invalue ) const {
double v = static_cast<double> ( invalue );
if ( v < MinimumInput ) {
v = MinimumInput;
} else if ( v > MaximumInput ) {
v = MaximumInput;
}
double interpolationfactor = ( v - MinimumInput ) / ( MaximumInput - MinimumInput );
return static_cast<RangeType> ( ( interpolationfactor * ( MaximumOutput - MinimumOutput ) ) + MinimumOutput );
}
};
.....
The astyle command:
astyle
\ --style=java
\ --indent=force-tab=2
\ --indent-classes
\ --indent-switches
\ --indent-labels
\ --indent-preprocessor
\ --indent-col1-comments
\ --pad-oper
\ --pad-paren
\ --delete-empty-lines
\ --add-brackets
\ --align-pointer=type
\ --align-reference=type
Is that a bug of astyle, or I forget any options?
If it is a bug, what could you suggest to format C++ code with VIM?
Sure, it's a bug. AStyle is not supported well these days. There are lots of bugs that were sitting there forever and never got resolved. You shouldn't expect the situation to improve in the nearest future. I highly recommend switching to Uncrustify. Certainly, it has some issues too, but they are not so nasty and do not break your code like AStyle does. It has hundreds of configuration options - much more flexible than AStyle - so be patient you'll have to spend quite some time to tweak it to your tastes and conventions.
When you are done and if you'd like to integrate it with Vim properly, here you go the code you could add into your .vimrc:
" Restore cursor position, window position, and last search after running a
" command.
function! Preserve(command)
" Save the last search.
let search = #/
" Save the current cursor position.
let cursor_position = getpos('.')
" Save the current window position.
normal! H
let window_position = getpos('.')
call setpos('.', cursor_position)
" Execute the command.
execute a:command
" Restore the last search.
let #/ = search
" Restore the previous window position.
call setpos('.', window_position)
normal! zt
" Restore the previous cursor position.
call setpos('.', cursor_position)
endfunction
" Specify path to your Uncrustify configuration file.
let g:uncrustify_cfg_file_path =
\ shellescape(fnamemodify('~/.uncrustify.cfg', ':p'))
" Don't forget to add Uncrustify executable to $PATH (on Unix) or
" %PATH% (on Windows) for this command to work.
function! Uncrustify(language)
call Preserve(':silent %!uncrustify'
\ . ' -q '
\ . ' -l ' . a:language
\ . ' -c ' . g:uncrustify_cfg_file_path)
endfunction
Now you can either map this function (Uncrustify) to a combination of keys or you could do the convenient trick that I use. Create a file ~/.vim/after/ftplugin/cpp.vim where you can override any Vim settings particularly for C++ and add the following line there:
autocmd BufWritePre <buffer> :call Uncrustify('cpp')
This basically adds a pre-save hook. Now when you save the file with C++ code it will be automatically formatted by Uncrustify utilizing the configuration file you supplied earlier.
NOTE: Everything presented here is well-tested and used every day by me.