I think currently the cleanest and easiest way to integrate C ++ (or C in your case) code is to use Rcpp package (CRAN link) (package website here) .
With Rcpp you can define a function in the section itself using the function cppFunction
:
library(Rcpp)
cppFunction('int soma(int x, int y){
int soma = x+y;
return soma;
}')
soma(1,2)
[1] 3
Or you can also define its functions in a .cpp
file and use the sourceCpp
function. You will specify in the header of the file that you are using Rcpp #include <Rcpp.h>
, using namespace Rcpp;
and then define its functions. If you are using RStudio, when asking to create a new c ++ file it already gives you the minimum file structure.
#include <Rcpp.h>
using namespace Rcpp;
// This is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp
// function (or via the Source button on the editor toolbar). Learn
// more about Rcpp at:
//
// http://www.rcpp.org/
// http://adv-r.had.co.nz/Rcpp.html
// http://gallery.rcpp.org/
//
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
return x * 2;
}
// You can include R code blocks in C++ files processed with sourceCpp
// (useful for testing and development). The R code will be automatically
// run after the compilation.
//
/*** R
timesTwo(42)
*/
Well, that's enough to get you started trying to pass the code to R. For more details I recommend the Hadley's book for a more general introduction and package vignettes and the Dirk book for more details about Rcpp.