Skip to content

Sleepingwell/SimpleEmbeddedR

Repository files navigation

This is a very simple example of how to embed R in another language. It might be useful for calling R on a when you only need to get text back.

However, R is not reentrant, so this will be racy if running on a server.

Introduction

The function defined here evaluates an arbitrary set of R expressions, and if the the last expression returns a 'string', will return that string.

The interface is generated using SWIG (www.swig.org).

Files

  • SimpleEmbeddedR.i: SWIG definition file,

  • init.h: Declares the funcitons to setup and tear down R,

  • SimpleEmbeddedR.h: Contains the declaration of the exposed function,

  • library_attach.cpp: Calls the functions defined in init.h when the library is attached/detached,

  • SimpleEmbeddedR.cpp: Defines the function declared in SimpleEmbeddedR.h,

  • init.cpp: Defines the functions declared in init.h,

  • embed_java.cpp: C++ side of bindings for Java (generated by SWIG),

  • embedr/: Java classes for the bridge between Java and C++ (generated by SWIG),

  • Tests.java: A Java class that shows how one would use this.

Generating and Compiling Language Bindings

To generate bindings for Java, you would say this:

swig -c++ -java -package "embedr" -o embed_java.cpp -outdir "embedr" SimpleEmbeddedR.i

For Python you would say:

swig -c++ -python -o embed_python.cpp SimpleEmbeddedR.i

Note that to run it, you need to make sure that R.<dll/so> is on the path.

For other languages (and SWIG supports a lot of them), please see the SWIG doco.

You then need to setup your build environment. For windows plebs (like me) you can see how I've setup the environment (for Java and Python) in the visual studio files herein.

with gcc, a line like:

gcc -I/path/to/directory/containing/java/jni/header -I/path/to/directory/containing/java/jni_md/header -I/path/to/R/include/directory -L/path/to/lib/directory -lR --shared -olibSimpleEmbeddedR.so embed_java.cpp init.cpp library_attach.cpp SimpleEmbeddedR.cpp

should do it... though I've not tested this.

Happy to help

If this does not make sense, let me know and I can try and help. I didn't want to write a whole lot more detail here or spend too much time making the code wonderful until I knew that someone is interested.

About

A simple example of how to embed R in other languages.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published