Why does object creation give segmentation fault in DLL?

evilrat evilrat666 at gmail.com
Sat Feb 22 03:08:40 PST 2014


On Saturday, 22 February 2014 at 09:09:42 UTC, Tolga Cakiroglu 
wrote:
> I have written a DLL file in Linux (x86_64). It is as below:
>
> File: lib.dll
> =====================
> class A{}
>
> extern(C) void foo(){
> 	Object obj = new Object();   // test 1
>
> 	A objA = new A();  // test 2
>
> 	char[] c = new char[ 1024 ];   // test 3
> }
>
>
> Compilation code is below:
> 	dmd -c lib.d -fPIC -debug
> 	gcc --shared lib.o -o lib.so
>
>
> Output of programme is like that:
> library is loaded now
> foo() function is found
> unloading libdll.so
> Segmentation fault (core dumped)
>
>
> Situation is that if either only the `test 1` or `test 3` code 
> is available in the function, there is no error at all. But 
> once I use `test 2` code, it starts giving segmentation fault. 
> Please notice that both `test 1` and `test 2` are creating an 
> object already. And all of them allocates memory with `new` 
> keyword. But only the `test 2` fails. Why is this happening?

you should init runtime in library and set gc proxy for it(if 
implemented on linux, otherwise you would have two gc's running 
simultaneously)

so add following methods to your lib.


// lib side
void initRT()
{
import core.runtime();
Runtime.initilize();
}

extern(C) void  gc_setProxy(void* p);
void setGCProxy(void* gc)
{
gc_setProxy(gc);
}

// executable side

extern(C) void* gc_getProxy();

void main()
{
// load lib here
initRT();
setGCProxy(gc_getProxy());
// do stuff here...
}


More information about the Digitalmars-d-learn mailing list