How To Call D Code from Objective C?

Mike McKee via Digitalmars-d digitalmars-d at puremagic.com
Fri Dec 11 00:20:54 PST 2015


I found a way to call C from in Objective C. The big trick is to 
rename a .m file to a .mm file. So, I think there's probably a 
way for me to link a compiled C dylib into Objective C and then 
load its .h header file so that Objective C can call those C 
functions.

I'll be using GCC to statically combine the D's .o code in with 
the C code.

So, I'm thinking the process is like this:

1. Create a D function d_test() that takes a string input, 
concatenates on "-response", and returns the result. Compile as 
dtest.o with "dmd -c dtest.d".

2. Create a C function c_test() that takes a string input, calls 
d_test() and passes it the string, and then returns the response 
from d_test() out of c_test() as a string result. Compile as 
ctest.dylib with "gcc -dynamiclib -o ctest.dylib ctest.c dtest.o 
-L/usr/local/lib -lphobos2 -lpthread -lm".

3. In Xcode IDE, add this ctest.dylib linked library. Then, 
create a ctest.h for the function declaration.

4. In Objective C, import ctest.h in my main.mm file and then 
call with something like NSLog("RESULT=%s",c_test("request"));  
That should create a debugger line that reads: 
RESULT=request-response.

The problem is that I don't know the entire way that I should 
create dtest.d and ctest.c.



More information about the Digitalmars-d mailing list