Using D as a shared library.
Paolo & Kevin
paolo.bolzoni at g.invalid
Tue May 14 06:53:31 PDT 2013
I am trying to use a D shared library with a C program.
But I have a problem, the code works in a D program.
But it crashes as a library.
Here is a minimal example.
I want to make a library that returns an array of 100 integers.
% ls
fakemain.d function.d main.c
% cat fakemain.d
void main() {}
% cat function.d
extern (C) {
int* blah() {
int[] a;
a.length = 100;
return a.ptr; } }
% cat main.c
int* blah();
int main() {
int* p;
p = blah();
p[0] = 1;
return p[0];}
%
Lets compile everything:
% dmd -fPIC -c fakemain.d
% dmd -fPIC -c function.d
% gcc -c main.c
% ls
fakemain.d fakemain.o function.d function.o main.c main.o
Lets link, fakemain.o is needed to avoid linking problems:
% gcc -fPIC -shared -o libfunction.so function.o
% gcc -L"$PWD" main.o fakemain.o -lfunction -lphobos2
% ls
a.out* fakemain.d fakemain.o function.d function.o
libfunction.so* main.c main.o
Lets try...
% LD_LIBRARY_PATH="$PWD" ./a.out
[1] 31468 segmentation fault (core dumped)
LD_LIBRARY_PATH="$PWD" ./a.out
% LD_LIBRARY_PATH="$PWD" gdb -q ./a.out
Reading symbols from
/home/paolo/uni/ostar/ostar/c_exact_algorithm/tmp/a.out...(no
debugging symbols found)...done.
(gdb) run
Starting program:
/home/paolo/uni/ostar/ostar/c_exact_algorithm/tmp/a.out
warning: Could not load shared library symbols for
linux-vdso.so.1.
Do you need "set solib-search-path" or "set sysroot"?
Program received signal SIGSEGV, Segmentation fault.
0x00000000004037d1 in gc_qalloc ()
(gdb) bt
#0 0x00000000004037d1 in gc_qalloc ()
#1 0x000000000040199c in _d_arraysetlengthT ()
#2 0x00007ffff7bda842 in blah () from
/home/paolo/uni/ostar/ostar/c_exact_algorithm/tmp/libfunction.so
#3 0x0000000000400ad2 in main ()
(gdb)
It fails :(
What I am doing wrong?
I think there is something the D language does before starting
main.
And the C language does not. Can I initialize the program
correctly
manually? Or it is another problem altogether?
Thanks,
Paolo & Kevin
More information about the Digitalmars-d-learn
mailing list