How to use @safe when a C library integration needed

Paul Backus snarwin at gmail.com
Fri Apr 14 16:19:22 UTC 2023


On Friday, 14 April 2023 at 14:10:41 UTC, Leonardo wrote:
> Thanks. But this works only to one function per time. Is there 
> any way to do this to an imported library at all? something 
> like `@trusted import library`

No, there isn't. C is an unsafe language, so if you want to call 
C from `@safe` code, you have to do the work to make sure that 
each individual call is `@safe`.

If you are calling the same C function many times from `@safe` 
code, you can write a `@trusted` D wrapper function to avoid 
repeating the safety checks at every call site. For example, 
here's a `@trusted` wrapper for the standard C library function 
`puts`:

```d
import core.stdc.stdio: puts;
import std.exception: enforce;

@trusted
void safePuts(const(char)[] s)
{
     // To safely call puts, we must pass it a valid C string
     // To be a valid C string, s must be non-empty and 
NUL-terminated
     enforce(s.length > 0, "An empty string is not a C string");
     enforce(s[$-1] == '\0', "A C string must be NUL-terminated");

     // If the checks above have passed, this call is safe
     puts(&s[0]);
}
```


More information about the Digitalmars-d-learn mailing list