Thread overview
Exec function D from C++
Jun 21, 2015
MGW
Jun 21, 2015
Sean Campbell
Jun 21, 2015
Jacob Carlborg
June 21, 2015
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.
June 21, 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;
}

June 21, 2015
On 21/06/15 16:09, Sean Campbell wrote:

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

These two functions are not necessary. There are already functions in druntime which are supposed to be called from C/C++:

extern (C) bool rt_init();
extern (C) bool rt_term();

-- 
/Jacob Carlborg