Best way to use large C library in D as of 2024

Lance Bachmeier no at spam.net
Mon Apr 1 02:08:20 UTC 2024


On Saturday, 30 March 2024 at 05:01:32 UTC, harakim wrote:
> On Tuesday, 26 March 2024 at 20:42:00 UTC, Chris Piker wrote:
>> On Tuesday, 26 March 2024 at 20:19:27 UTC, bachmeier wrote:
>>>
>>> Should be able to just use it, as described here: 
>>> https://forum.dlang.org/post/qxctappnigkwvaqakeqf@forum.dlang.org Create a .c file that includes the header files and then call the functions you need.
>>
>> Wow. **That just worked the first time!**  Holy &^@$ that's 
>> easy!
>>
>> So why does the 2nd page returned from the google search
>> ```
>> interfacing with C site:dlang.org
>> ```
>> (which happens to be: 
>> https://dlang.org/spec/interfaceToC.html) still have this text:
>>
>>> Since D can call C code directly, it can also call any C 
>>> library functions,
>>> giving D access to the smorgasbord of existing C libraries. 
>>> To do so, however,
>>> one needs to write a D interface (.di) file, which is a 
>>> translation of the C .h
>>> header file for the C library into D.
>>> 
>>> For popular C libraries, the first place to look for the 
>>> corresponding D interface
>>> file is the Deimos Project. If it isn't there already, please 
>>> write and contribute
>>> one to the Deimos Project.
>> ?
>>
>> This lead me to believe that interfacing was a chore and I was 
>> considering going back to C for a small program I need.
>
> @D Language Foundation - This is a HUGE selling point. I had to 
> use cups the other day and I just copied some code from a d 
> file and linked the library. It was so easy I was suspicious 
> but it worked. Using C from D is pretty much as easy as using C 
> from C and I think you should advertise that better!

It works well if you only need to work with a header. There are 
still a few rough edges that get in the way if you're compiling 
the full C sources (I filed bugs for all of them):

- Can't handle va_arg
- Can't cast to a pointer of a struct that's typedef'd
- Can't use complex numbers with the ternary operator

These problems should be cleaned up before heavily promoting what 
is an incredible feature. I don't think it's widely known that 
you can translate C source files into D. I think that's really 
cool, but in addition to the bugs listed above that ImportC can't 
handle, it outputs things like dpulicate aliases, function 
argument names that are D keywords, and declaring unions inside 
structs equal to void. All of these are easy to fix by hand, but 
it's time consuming.

Once these final odds and ends are working, we have a killer 
language feature.


More information about the Digitalmars-d-learn mailing list