D2: Call writefln in D shared libraries from C side

I am trying to quickly run dynamic shared libraries in D, but I have a problem.

I am dmd -shared ./testlib.d following code with dmd -shared ./testlib.d :

 module testlib; import std.c.stdio; extern (C) export int hello(int a) { printf("Number is %d", a); return (a + 1); } 

It builds great and works. But when I try to use the following D'ish source:

 module testlib; import std.stdio; extern (C) export int hello(int a) { writefln("Number is %d", a); return (a + 1); } 

It does not work with segmentation error when I try to call hello . What am I doing wrong?

I call hello using Python:

 import ctypes testlib = ctypes.CDLL('testlib.dylib'); print (testlib.hello(10)) 

UPD1: It seems that I also cannot use Phobos functions like std.conv.to!(string) .

UPD2: There are no such problems in Windows, everything works fine. Mac OS X suffers from this.

UPD3: Perhaps this is due to the GC. I have to somehow initialize the GC, but core.memory.GC.enable () still does not work with a segmentation error.

+6
source share
1 answer

The solution is simple but brilliant:

 static import core.runtime; extern (C) export void init() { // to be called once after loading shared lib core.runtime.Runtime.initialize(); } extern (C) export void done() { // to be called before unloading shared lib core.runtime.Runtime.terminate(); } 

There may be ways in Linux and Mac OS X to call these functions automatically, but I'm even happy with that.

+5
source

Source: https://habr.com/ru/post/911029/


All Articles