Created
March 6, 2010 04:44
-
-
Save Sharpie/323498 to your computer and use it in GitHub Desktop.
An example of calling R functions from C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//myRunif.c | |
#include <R.h> | |
#include <Rinternals.h> | |
SEXP myRunif( SEXP n, SEXP min, SEXP max ){ | |
SEXP statsPackage; | |
PROTECT( | |
statsPackage = eval( lang2( install("getNamespace"), | |
ScalarString(mkChar("stats")) ), | |
R_GlobalEnv | |
) | |
); | |
SEXP RCallBack; | |
PROTECT( RCallBack = allocVector(LANGSXP, 4 )); | |
SETCAR( RCallBack, | |
findFun( install("runif"), statsPackage ) | |
); | |
SETCADR( RCallBack, n ); | |
SET_TAG( CDR( RCallBack ), install("n") ); | |
SETCADDR( RCallBack, min ); | |
SET_TAG( CDDR( RCallBack ), install("min") ); | |
SETCADDDR( RCallBack, max ); | |
SET_TAG( CDR(CDDR( RCallBack )), install("max")); | |
SEXP randoms; | |
PROTECT( | |
randoms = eval( RCallBack, statsPackage ) | |
); | |
UNPROTECT(3); | |
return( randoms ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#myRunif.R | |
myRunif <- | |
function( n, min = 0, max = 1 ){ | |
unifRandom <- .Call( 'myRunif', n, min, max ) | |
return( unifRandom ) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Alternate myRunif.c | |
#include <R.h> | |
#include <Rinternals.h> | |
SEXP myRunif( SEXP n, SEXP min, SEXP max ){ | |
SEXP statsPackage; | |
PROTECT( | |
statsPackage = eval( lang2( install("getNamespace"), | |
ScalarString(mkChar("stats")) ), | |
R_GlobalEnv | |
) | |
); | |
SEXP randoms; | |
PROTECT( | |
randoms = eval( lang4( install("runif"), | |
n, | |
min, | |
max), | |
statsPackage | |
)); | |
UNPROTECT(2); | |
return( randoms ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#zzz.R | |
.First.lib <- | |
function( libname, pkgname ){ | |
library.dynam( pkgname, pkgname, libname ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment