[Rd] Accessing C++ code from R

Simon Urbanek simon.urbanek at r-project.org
Wed Apr 4 20:34:03 CEST 2007


Jos,

you omitted the crucial part but my guess would be that all you have  
to do is to put #include <iostream> *before* R headers includes (R  
defines "length" which throws off iostream).
Also note that using cout is not a good idea, because it is not  
captured by R, you should be using Rprintf instead.

Cheers,
Simon

On Apr 4, 2007, at 1:44 PM, Jos Elkink wrote:

> Hi,
>
> I am trying to use existing C++ code from R. I have no problems
> compiling C code and using it in R, but with C++ I'm running into
> problems.
>
> Here's the compiler output:
>
> Macintosh-10:~/Desktop/dissertation/Model - CPP version/R labguest$
> g++ -I/Library/Frameworks/R.framework/Resources/include
> -I/Library/Frameworks/R.framework/Resources/include/i386 *.cpp
> In file included from /usr/include/c++/4.0.0/bits/locale_facets.h: 
> 1533,
>                  from /usr/include/c++/4.0.0/bits/basic_ios.h:44,
>                  from /usr/include/c++/4.0.0/ios:50,
>                  from /usr/include/c++/4.0.0/ostream:44,
>                  from /usr/include/c++/4.0.0/iostream:44,
>                  from main.cpp:5:
> /usr/include/c++/4.0.0/bits/codecvt.h:217:45: error: macro "length"
> passed 4 arguments, but takes just 1
> /usr/include/c++/4.0.0/bits/codecvt.h:216: error: expected ';'  
> before 'const'
> /usr/include/c++/4.0.0/bits/codecvt.h:220: error: expected `;'  
> before 'int'
> main.cpp:51: error: brace-enclosed initializer used to initialize
> 'R_NativePrimitiveArgType*'
>
>
> Line 51 refers to the standard part to register the function in R:
>
> R_CMethodDef cMethods[] = {
>   {"runSimulation", (void* (*) ()) &runSimulation, 27, {INTSXP,
> INTSXP, INTSXP, REALSXP, REALSXP, REALSXP, INTSXP, INTSXP, INTSXP,
> INTSXP, INTSXP, INTSXP, REALSXP, REALSXP, INTSXP, INTSXP, INTSXP,
> INTSXP, INTSXP, INTSXP, INTSXP, INTSXP, INTSXP, INTSXP, REALSXP,
> REALSXP, REALSXP}},
>   {NULL, NULL, 0}
> };
>
>
> I had to add the explicit cast of &runSimulation to get rid of one
> compiler error, but do not know how to deal with this one.
> Encapsulating this part of the code in
>
> extern "C" {
> }
>
> has no effect.
>
> runSimulation is just a regular function, with a lot of int* and
> double* parameters, and it is not part of a class. It does inside
> create a class, though.
>
> Outline:
>
> void runSimulation(int *p_1 ... etc) {
>
>    try {
>      CModel Model();
>      Model.Run();
>    } catch (CException& e) {
>      cout << "exception" << endl;
>    }
> }
>
> Encapsulating this function in extern "C" also has no effect.
>
> Anyone any ideas what I should do? The system I am using is an  
> Intel-based Mac.
>
> Thanks in advance!
>
> Jos
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>



More information about the R-devel mailing list