How To Call D Code from Objective C?

Mike McKee via Digitalmars-d digitalmars-d at puremagic.com
Thu Dec 10 23:29:09 PST 2015


Okay, so what has been shared is that the first step is to get C 
to call D, because if I can do that, then I can get Obj C to call 
C since there's no direct bridge to D. Obj C has a way to call C.

So, I found this article:

http://www.prowiki.org/wiki4d/wiki.cgi?DcalledFromC

I also found it's not quite up to date with the latest DMD. Here 
are some things I didn't have to do:

* If you scroll to the bottom, it talks about needing a main() in 
D. That's no longer necessary. So, the file in the example 
Dmaindummy.d is no longer required. This meant that I could edit 
Cmain.c and remove the print line there because it was irrelevant.

* One needs to use phobos2 instead of phobos. On Ubuntu 14.04, I 
did apt-get install dmd to get the D compiler, and then did 
apt-cache search libphobos to see which one was the latest it 
had, and then in my case I did apt-get install libphobos2-69, but 
your situation may vary.

* This changes the compilation a little, and I lowercased the 
filenames to make it easier for me:

$ dmd -c dfunc.d
$ gcc cmain.c dfunc.o -o ctest -lphobos2 -lpthread -lm

I then could call ctest with:

$ ./ctest

Note on OSX, the GCC line is a little different. If you've 
installed dmd from homebrew, it doesn't write to /usr/lib (that's 
locked down now) but does write to /usr/local/lib and 
/usr/local/include. So, you have to tell GCC to call that path 
with the -L parameter because it doesn't do that by default for 
some strange reason on OSX:

$ gcc cmain.c dfunc.o -o ctest -L/usr/local/lib -lphobos2 
-lpthread -lm

This then made it find /usr/local/lib/libphobos2.a with that 
-lphobos2 parameter.

So, then it worked on OSX too.

And now to figure out how to make a C library instead of an 
executable, and then how to load that compiled library in 
Objective C, load a header (.h file) in Objective C for that C 
function, and call the C function, which then calls the D 
function.

I'll update you if I figure all that out...



More information about the Digitalmars-d mailing list