Skip to content

Help: Using R from C

2 messages · Prasad, Rajiv, Brian Ripley

#
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.

Rajiv.
--------
Rajiv Prasad							(509) 375-2096
(Voice)
Postdoctoral Research Associate, Hydrology Group	(509) 372-6089	(Fax)
Pacific Northwest National Laboratory			rajiv.prasad at pnl.gov
P.O. Box 999, MSIN K9-33, Richland, WA 99352

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
On Wed, 28 Mar 2001, Prasad, Rajiv wrote:

            
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).