brendano (owner)

Revisions

  • 07006f Thu Jul 24 00:56:48 -0700 2008
gist: 2079 Download_button fork
public
Public Clone URL: git://gist.github.com/2079.git
Embed All Files: show embed
r_sample_extension.cc #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/////////////////////////////////////////
// Sample for Embedding C++ into R //
/////////////////////////////////////////
//
// I keep forgetting how to do this so here's an example.
// If you're willing to use R's most primitive FFI interface,
// things are incredibly simple and easy to get going.
// -Brendan O'Connor (brenocon@gmail.com)
//
// Compile with, e.g. on mac:
// $ g++ -dynamic -bundle -I/Library/Frameworks/R.framework/Resources/include ext.cc -o ext.dylib
// And from R:
// > dynload("ext.dylib")
// > .C("hi")
// Hello Earth
// list()
//
// .C() is very low level. To pass data in and out, you get raw pointers
// to the internal vectors that R itself uses. I think.
//
// > .C("mul_2", as.integer(1:3), as.integer(3), as.integer(rep(-1,3)))
// [[1]]
// [1] 1 2 3
//
// [[2]]
// [1] 3
//
// [[3]]
// [1] 2 4 6
//
// Documentation: http://cran.r-project.org/doc/manuals/R-exts.html#Interface-functions-_002eC-and-_002eFortran
 
 
#include <R.h>
#include <iostream>
using namespace std;
 
extern "C" {
 
void hi()
{
  cout << "Hello Earth" << endl;
}
 
void mul_2(int* numbers, int* n, int* output)
{
  for (int i=0; i < *n; i++) {
    output[i] = numbers[i] * 2;
  }
}
 
 
}