Exec function D from C++

Sean Campbell via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 21 07:09:46 PDT 2015


On Sunday, 21 June 2015 at 13:12:03 UTC, MGW wrote:
> Linux 32, dmd 2.067.0
>
> I want to connect and execute function D from main() C++.
>
> ---- d1.d ----
> import core.stdc.stdio;
>
> extern (C++) void d1() {
>     printf("printf - exec d1()");
> }
>
> ---- main_c1.cpp ----
> #include <stdio.h>
>
> void d1(void);
>
> int main(void) {
>     d1();
>     return 0;
> }
>
> ---- compile ----
> dmd -c d1.d
> gcc main_c1.cpp d1.o libphobos2.a -lpthread -o main_c1
> ./main_c1  --->  This option works correctly!
>
>
> If I try to cause the functions connected to GC in the D 
> function, there is an error.
> ---- d1.d ----
> import import std.stdio;
>
> extern (C++) void d1() {
>     writeln("writeln - exec d1()");
> }
>
> ---- compile ----
> dmd -c d1.d
> gcc main_c1.cpp d1.o libphobos2.a -lpthread -o main_c1
> ./main_c1  --->  Error:
> './main_c1' terminated by signal SIGSEGV (Address boundary 
> error)
>
> Examples from dmd2/html/d/dll-linux.html don't work if instead 
> of printf()
> to use writeln(). I think that a problem in initialization of 
> Phobos.

actually its that druntime hasn't been initialized just add:
import core.runtime;
import std.stdio;

extern(C++) void d1() {
      writeln("writeln - exec d1()");
}

extern(C++) void d_initialize() {
      Runtime.initialize();
}
extern(C++) void d_terminate()
{
      Runtime.terminate();
}

and the C++
#include <stdio.h>

void d1(void);
void d_initialize(void);
void d_terminate(void);

int main(void) {
     d_initialize();
     d1();
     d_terminate();
     return 0;
}



More information about the Digitalmars-d-learn mailing list