C to D bindings: how much do you D-ify the code?

John Colvin john.loughran.colvin at gmail.com
Fri Oct 25 09:22:44 PDT 2013


On Friday, 25 October 2013 at 13:26:33 UTC, John Colvin wrote:
> On Friday, 25 October 2013 at 13:10:05 UTC, Lionello Lunesu 
> wrote:
>> There's a lot of expressiveness that can be added to D 
>> bindings, when compared to the C or C++ headers, for a 
>> particular library:
>>
>> 1. enum names vs prefixes
>> enum FOO { FOO_A, FOO_B }; -> enum FOO {A,B}
>>
>> 2. enum vs int parameters (based on a lib's documentation)
>> void takefoo(int) -> void takefoo(FOO)
>>
>> 3. "in" for input buffers (again, based on docs)
>> int puts(char*) -> puts(in char*)
>>
>> 4. "out" or "ref" for output parameters
>> void getdouble(double*) -> void getdouble(out double value)
>>
>> 5. D arrays vs length+pointer pairs
>> void bar(size_t len, int* ptr) -> void bar(int[] a)
>>
>> 6. D array wrappers
>> void bar(int* ptr, int size) ->
>> void bar(int[] a) { bar(a.ptr, cast(int)a.length; }
>>
>> 6. library specific sized-int typedefs to D natives
>> png_uint_16 -> short
>>
>>
>> These are some of the more trivial ones, but I'd like to see 
>> how other people go about making bindings. Do you keep as 
>> close to C as possible? Or do you "add value" by using more D 
>> style constructs?
>>
>> L.
>
> I would go for a two stage approach:
>
> 1) Write bindings that map as closely as possible to the C API, 
> only adding anything extra by necessity and/or where it is 
> transparent in correct usage.

As an aside, I would suggest that function overloads that take 
arrays instead of pointer + length is normally a harmless 
addition to an otherwise 1:1 set of bindings.


More information about the Digitalmars-d mailing list