Bug 23812 – ImportC: allow adding function attributes to imported C functions
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2023-03-28T13:54:19Z
Last change time
2024-09-14T17:58:09Z
Keywords
ImportC, industry, pull
Assigned to
No Owner
Creator
Dennis
Comments
Comment #0 by dkorpel — 2023-03-28T13:54:19Z
C functions imported with ImportC currently don't get any function attributes, so they're currently not callable in `nothrow` `@nogc` `pure` `@safe` contexts.
nothrow and @nogc could be given by default, the only exceptions would be if the imported function has a callback, or if it is actually implemented in D but imported through a C file for some reason.
@safe is rarer for C functions since they often receive raw pointers, so we might just require use of `@trusted` when calling them from a `@safe` context.
pure is also rarer for C, since C libraries often use global variables / stderr for error reporting, but ImportC could recognize the `__attribute__((pure))` extension some compilers have.
In any case, new syntax could be created along the lines of:
```C
#pragma nogc nothrow
#include <somelibrary.h>
```
Comment #1 by schveiguy — 2023-09-04T11:44:12Z
Yes, I had to remove the nogc and nothrow attributes from my project to get it compiling with importc usage.
I think the defaults have to be as is since we don’t have negation of pure nogc nothrow. But I agree that a pragma would suffice.
Comment #2 by aliloko — 2024-05-14T18:12:03Z
I've translated a fair share of C and AFAIK they all could be `nothrow @nogc`.
Comment #3 by dlang-bot — 2024-08-29T17:51:13Z
@tim-dlang created dlang/dmd pull request #16820 "Fix bugzilla 23812 - ImportC: allow adding function attributes to imp…" fixing this issue:
- Fix bugzilla 23812 - ImportC: allow adding function attributes to imported C functions
This adds a new pragma for ImportC, which allows to set default storage
classes. Only `nothrow`, `@nogc` and `pure` are supported for now.
They can be disabled later with the same pragma using a minus.
Unknown pragmas are ignored.
The pragma starts with identifier `D` to avoid conflicts.
https://github.com/dlang/dmd/pull/16820
Comment #4 by dlang-bot — 2024-09-14T17:58:09Z
dlang/dmd pull request #16820 "Fix bugzilla 23812 - ImportC: allow adding function attributes to imp…" was merged into master:
- d956dc0ccc458a8506a2776ebc1eb00ef5127685 by Tim Schendekehl:
Fix bugzilla 23812 - ImportC: allow adding function attributes to imported C functions
This adds a new pragma for ImportC, which allows to set default storage
classes. Only `nothrow`, `@nogc` and `pure` are supported for now.
They can be disabled later using `#pragma attribute(pop)`.
Unknown storage classes are ignored.
https://github.com/dlang/dmd/pull/16820