[R] Help: Using R from C

Prof Brian D Ripley ripley at stats.ox.ac.uk
Thu Mar 29 07:47:49 CEST 2001


On Wed, 28 Mar 2001, Prasad, Rajiv wrote:

>
> Hi folks:
>
> I am just beginning to try and use R from my own C programs.  Platform is
> Windows2000, compiler Visual C++ 6.0.  I built the import library R.lib from
> R.dll using the VC LIB.exe program.  Here is a simple code I am trying to
> compile and run (no C++, VC++ is instructed to treat it strictly as C):
>
> #include "R.h"
> #include "Rinternals.h"
>
> int main(void)
> {
> 	int i;
> 	char *greeting;
> 	SEXP x;
>
> 	greeting = (char *) Calloc(31, char);
> 	sprintf(greeting, "\nCallRFromC: test 1\n");
> 	printf(greeting);
>
> 	printf("Here is a vector:\n");
>
> 	/* allocate an R vector */
> 	PROTECT(x = allocVector(REALSXP, 10));
> 	for(i=0; i<10; i++) {
> 		REAL(x)[i] = (double)i;
> 		printf("  x[%2d] = %lf\n", REAL(x)[i]);
> 	}
> 	UNPROTECT(1);
>
> 	return 0;
> }
>
> The code builds without any problem (I am linking it with the import library
> R.lib, and R.dll is in the path).  While running, though, the code segfaults at
> the allocVector(...) call.  The error message is [The instruction at
> "0x002ee77e" referenced memory at ")x0000000c". The memory could not be "read".
> Click on OK to terminate the program]
>
> Stepping into the code using the debug mode, the crash happens at the
> allocVector(...) call.
>
> Am I missing something obvious here?  Any help is greatly appreciated.

Um.  Wherever did you get the idea that would work?  You have not
initialized R.  The examples given are to start and run the R main loop.
Even if you get this to work (and I think you can by looking carefully at
what the code in main.c does), you will have to cope with the R error
handler which longjmps to the R main loop.

You didn't say what you were trying to do with R from your C program.
Either follow the examples in src/gnuwin32/front-ends precisely and use
callbacks or multiple threads, or use the DCOM R server on CRAN (which is a
lot easier to use).

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list