About me | pbdR Tech | HPSC | Phyloclustering | R_note |

 R_note -- The Exploration of Statistical Software R (統計軟體 R 深度歷險)
Reference
MS Windows

Batch jobs
Function
Data/MySQL
Plot
String/Parse

Remark Lines
Classes/S3
S4 Methods
Batch more
Environment

Good Coding
Fast Loop
LAM/MPI/Rmpi
Recursion

PHP Call R
Basic C
R Call Fortran/C
R Call GSL
C Call R API
C Call R Objects
Standalone

Make Packages
C Pointer
Debug

Section: C Call R API

• Reference
Read the web page The R Manuals, and the PDF document Writing R Extensions (Chapter 5) in The R Manuals (my mirror here).

• C code
The C code "callR.c" will generate 10 random variables from standard normal (mu = 0, sigma = 1) and compute theirs cumulative probability, and sort these 10 random variables, and print all results.

 ``` #include #include void callR(){ int i; double mu, sigma, PHI_X, *X; mu = 0; sigma = 1; X = (double *) R_alloc(10, sizeof(double)); Rprintf("Before sort\n"); GetRNGstate(); for(i = 0; i < 10; i++){ X[i] = rnorm(mu, sigma); PHI_X = pnorm(X[i], mu, sigma, 1, 0); Rprintf("X: %f, PHI(X): %f\n", X[i], PHI_X); } PutRNGstate(); R_rsort(X, 10); Rprintf("After sort\n"); for(i = 0; i < 10; i++){ PHI_X = pnorm(X[i], mu, sigma, 1, 0); Rprintf("X: %f, PHI(X): %f\n", X[i], PHI_X); } } ```

• Compile
Linux:
 ``` SHELL> gcc -shared -o callR.so callR.c -I/usr/lib/R/include/ -L/usr/lib/R/bin/ -lR ``` or ``` SHELL> R CMD SHLIB callR.c ```

The output will be a shared library "callR.so" which is a dynamic loading file as the dll file in MS Windows.

• R script
Create a R script "callR.r" to load the library and execute it.

 ``` dyn.load("callR.so") set.seed(10) out <- .C("callR") dyn.unload("callR.so") ```

• Output
The output is as the following,

 ``` Before sort X: 0.018746, PHI(X): 0.507478 X: -0.184253, PHI(X): 0.426908 X: -1.371331, PHI(X): 0.085136 X: -0.599168, PHI(X): 0.274531 X: 0.294545, PHI(X): 0.615829 X: 0.389794, PHI(X): 0.651656 X: -1.208076, PHI(X): 0.113509 X: -0.363676, PHI(X): 0.358050 X: -1.626673, PHI(X): 0.051903 X: -0.256478, PHI(X): 0.398791 After sort X: -1.626673, PHI(X): 0.051903 X: -1.371331, PHI(X): 0.085136 X: -1.208076, PHI(X): 0.113509 X: -0.599168, PHI(X): 0.274531 X: -0.363676, PHI(X): 0.358050 X: -0.256478, PHI(X): 0.398791 X: -0.184253, PHI(X): 0.426908 X: 0.018746, PHI(X): 0.507478 X: 0.294545, PHI(X): 0.615829 X: 0.389794, PHI(X): 0.651656 ```

• Question
Why not to use executable file? How to build a "callR.exe"?
See Standalone.

 [ Go to top ]

 Maintained: Wei-Chen Chen E-Mail: wccsnow @ gmail.com Last Revised: Dec 12 2016, 09:44 (CST Taipei, Taiwan) Created: Oct 06 2003 Best Resolution IE6.0 1280x1024 small font