[R] Re: help in R calling C function (Lei Liu)

Zhu Wang zhuw at mail.smu.edu
Sun Jun 27 10:27:52 CEST 2004


> Message: 4
> Date: Sun, 27 Jun 2004 03:18:43 -0400
> From: Lei Liu <liulei at l.imap.itd.umich.edu>
> Subject: [R] help in R calling C function
> To: r-help at stat.math.ethz.ch
> Message-ID: <5.1.0.14.1.20040627030746.014936b8 at l.imap.itd.umich.edu>
> Content-Type: text/plain; charset="us-ascii"; format=flowed
> 
> Hi there,
> 
> I want to call a C function in R. I have some experience on it, but this 
> time I need to call another C function in the "main" C function. As a 
> simple example, I use the following C code:
> 
> #include <stdio.h>
> #include <math.h>
> #include <stdlib.h>
> #include <time.h>
> 
> 
> void main(double *alpha)
> {
> 	double test();
> 	double beta;
> 	beta= *alpha *2 + test(*alpha);
> }
> 
> double test(double *alpha)
> {
> 	double value;
> 	value = *alpha *3;
> 	return(value);
> }
> 
> I used "gcc -c main.c" and "Rcmd SHLIB main.o" and I got the main.dll file. 
> In R I use the following code to call the C function "main":

I do not have too much experience using C, but do you need to compile
your test.c as well, something like

gcc -c main.c test.c

> dyn.load("c:/Program Files/R/rw1060/bin/main.dll")

I also suggest you to double check the path is correct.
> a=4.2
> b=.C('main', as.double(a))

Here you probably mean

a <- 4.2
b <- .C('main',as.double(a))

> But the R system crashed. I know I can only define the function type in C 
> as "void" to be called by R. But what if I want to call another C function 
> in the "main" C function? Thank you for your help!
> 
> Sincerely,
> 
> Lei Liu
> 
> 
> 

-- 
Zhu Wang

Statistical Science Department
Southern Methodist University
Dallas, TX 75275-0332




More information about the R-help mailing list