Interfacing D to C R standalone math library

Jacob Carlborg doob at me.com
Wed May 30 23:19:33 PDT 2012


On 2012-05-30 21:20, TJB wrote:
> Hello!
>
> I am still wet behind the ears with D. I am trying to interface to an
> existing C library from the R standalone math library
> (www.r-project.org). I can call the library quite easily from a C++
> program as follows:
>
>
> #include <iostream>
> #include <time.h>
> #define MATHLIB_STANDALONE
> #include "Rmath.h"
>
> using namespace std;
>
> int main() {
> int i, n;
> double sum, x;
> time_t tt;
>
> tt = time(NULL);
>
> set_seed(tt, 77911);
>
> cout << "How many random normals to find the mean? ";
> cin >> n;
>
> sum = 0.0;
> for(i = 0; i < n; i++) {
> sum += rnorm(0, 1);
> }
>
> cout << "mean is " << sum/n << endl;
>
> return 0;
> }
>
> I can compile this with:
>
> $ g++ -o rnorm rnorm.cpp -I /usr/include -L /usr/lib -lRmath -lm
>
> When I grep rnorm from the Rmath.h header file I get:
>
> $ grep rnorm Rmath.h
> #define rnorm Rf_rnorm
> double rnorm(double, double);
>
> I have written D code to call this as follows:
>
> import std.stdio;
>
> extern (C) double rnorm(double, double);
>
> void main() {
> writeln(myfunc(0.0, 1.0));
> }
>
> double myfunc(double a, double b) {
> return rnorm(a, b);
> }
>
> But I don't know what I need to do to compile it. What flags do I add?
> What else do I have to do?
>
> Thanks for your help!
>
>

You just need to link to the external libraries.

$ dmd rnorm.d -L-L/usr/lib -L-lRmath -L-lm

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list