Basics of calling C from D

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 11 08:28:05 PDT 2014


On Wednesday, 11 June 2014 at 14:28:49 UTC, belkin wrote:
> On Wednesday, 11 June 2014 at 14:02:08 UTC, John Colvin wrote:
>> On Wednesday, 11 June 2014 at 13:52:09 UTC, belkin wrote:
>>> Example: I have this C function that is compiled into a 
>>> library
>>>
>>> //File: factorial.h
>>> int factorial(int n);
>>>
>>>
>>> //File: factorial.c
>>> #include "factorial.h"
>>>
>>> int factorial(int n)
>>> {
>>>   if(n!=1)
>>>    return n*factorial(n-1);
>>> }
>>>
>>> Question: How do I use it from D?
>>
>> //File: blah.d
>>
>> extern(C) int factorial(int n); //coincidentally identical to 
>> the C declaration.
>>
>> void main()
>> {
>>    assert(factorial(3) == 6);
>> }
>>
>>
>> $ gcc -c factorial.c -ofactorial.o
>> $ dmd blah.d factorial.o
>> $ ./blah
>>
>> or
>>
>> $ gcc -c factorial.c -ofactorial.o
>> $ ar rcs libfactorial.a factorial.o
>> $ dmd blah.d -L-lfactorial
>> $ ./blah
>>
>>
>>
>> Basically, you just translate the header files from C to D, 
>> then link to the C implementation. See 
>> http://code.dlang.org/packages/dstep for automatic translation 
>> of headers.
>
> This is great.
> How practical (reliable ) is it to translate a large and 
> complex header file like oci.h ( the interface for Oracle's 
> database API ) to D?

By hand it's just laborious, but it's very simple.

Using dstep: It doesn't handle any pre-processor stuff, so a lot 
of complicated headers are out of the question. One approach is 
to run the pre-processor in gcc over the file, use dstep on the 
output, then reconstruct the conditional compilation stuff 
manually.


More information about the Digitalmars-d-learn mailing list