On 2012-09-28 01:21, Rob T wrote:
For me to get C or C++ to run a D function, I had to do the following:

// ====================
// C/C++ library source
// ====================

// sample D function from library
void foo(int i, int j, int k);
// D runtime initialization & shutdown
void init();
void done();

void bar()
{
     foo(6, 7, 8);
}

int main(int argc, char **argv)
{
init();
     bar();
     done();
     return 0;
}


// ================
// D library source
// ================
import std.stdio;
static import core.runtime;

// sample D function for test
extern (C++) //    int foo(int i, int j, int k)
     void foo(int i, int j, int k)
     {
         writefln("i = %s", i);
         writefln("j = %s", j);
         writefln("k = %s", k);
         int t = i + j + k;
         writefln("Total = %s", t);
     }

// Had to initialize and shutdown D system from C/C++.
extern (C++) export void init() { // to be called once after loading
shared lib
     core.runtime.Runtime.initialize();
}

extern (C++) export void done() { // to be called before unloading
shared lib
     core.runtime.Runtime.terminate();
}


// I had to include main even though this is a library.
int main()
{
    return 0;
}

That is not sufficient to have everything work. It might be ok if you limit yourself to a C subset of D. On some platforms, calling Runtime.initialize, will miss initializing some parts.

The implementation of the runtime initialization contains a lot of code duplication and some functions/branches are missing functionality. Example:

https://github.com/D-Programming-Language/druntime/blob/master/src/rt/dmain2.d#L346

The C main function handles the runtime initialization for a regular statically linked executable. If you initialize the runtime via "rt_init", which is called by "Runtime.initialize", it will miss to initialize some parts on some platforms. The C main function should really call "rt_init" to remove the code duplication.

Also see this post why everything will not properly work:

http://forum.dlang.org/thread/k3vfm9$1tq$1...@digitalmars.com?page=3#post-k4219f:24uft:241:40digitalmars.com


--
/Jacob Carlborg

Reply via email to