dynamic library building and loading

Maxim Fomin maxim at maxim-fomin.ru
Thu Sep 27 03:26:32 PDT 2012


On Thursday, 27 September 2012 at 08:26:08 UTC, Jacob Carlborg
wrote:
>
> Last time I tried this (on Mac OS X) I got several symbols 
> missing. This was all symbols that are usually pointing to the 
> executable, inserted by the compiler. One of them would be 
> "main" and symbols like these:
>
> https://github.com/D-Programming-Language/druntime/blob/master/src/rt/deh2.d#L27

"_deh_" problem AFAIK arise when non-D and D code is merged and
can be avoided. For example, assume C/C++ application using D
library. This can be done by writing D main function which
forwards call to C/C++ main function which uses D shared library
code. Again, sorry for code post, dpaste isn't working:
---main.cpp---
extern "C" void foo(void);

#include <stdio.h>

class CPP
{
public:
     CPP() { printf("CPP ctor\n"); }
};

CPP cpp;

extern "C" int c_main_func()
{
     printf("C main function reached\n");
     foo();
     // C/C++ application
     return 0;
}
---dmain.d---
import std.stdio;

extern(C) int c_main_func();

static this()
{
     writeln("main module ctor");
}

static ~this()
{
     writeln("main module dtor");
}

int main()
{
     return c_main_func();
}
---test.d---
import std.stdio;

static this()
{
     writeln("lib module ctor");
}

static ~this()
{
     writeln("lib module dtor");
}

extern(C) void foo()
{
     auto a = new A("data");
     writeln("in foo");

}

class A
{
     string x;
     static this() { writeln("static ctor"); }
     static ~this() { writeln("static dtor"); }
     this(string x) { writeln("ctor"); this.x = x; }
     ~this() { writeln("dtor"); writeln(x); }
}
------
# g++ main.cpp -c
# dmd -c dmain.d
# dmd -c test.d -fPIC
# gcc -shared test.o -o libtest.so
# gcc dmain.o main.o -ltest -lphobos2 -lpthread -lrt -L.
-Wl,-rpath=.
# ./a.out
CPP ctor
main module ctor
lib module ctor
static ctor
C main function reached
ctor
in foo
static dtor
lib module dtor
main module dtor
dtor
data
# ldd ./a.out
	linux-vdso.so.1 (0x00007fff4cd55000)
	libtest.so => ./libtest.so (0x00007f970520b000)
	libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f9704fd3000)
	librt.so.1 => /lib64/librt.so.1 (0x00007f9704dcb000)
	libc.so.6 => /lib64/libc.so.6 (0x00007f9704a26000)
	/lib64/ld-linux-x86-64.so.2 (0x00007f970540e000)
#



More information about the Digitalmars-d mailing list