Calling C functions that modify a string

Pat Maddox pat at patmaddox.com
Thu Jun 15 03:29:28 UTC 2023


Hi there, I want to call a C function that upcases a string. I 
have something working, I just want to check in here to see if 
there's a better approach that I'm missing. I ask because 
`std.string.toStringZ()` returns an `immutable char *`.

As far as I can tell, I have two options:

1. Make the extern definition accept immutable.
2. Cast to `char *`.

I opted for 2 because it seems that 1 would be confusing - the 
definition says immutable, but it mutates the string.

Anyway, is this the D way to mutate a string from C, or is there 
another approach I'm unaware of?

```
extern (C) void upcase(char *);

import std.stdio;
import std.string;

void main() {
   auto s = "hello d";
   auto cs = cast (char *) std.string.toStringz(s);
   upcase(cs);
   writeln(std.string.fromStringz(cs));
}
```

It also works with:

```
extern (C) void upcase(immutable char *);

import std.stdio;
import std.string;

void main() {
   auto s = "hello d";
   auto cs = std.string.toStringz(s);
   upcase(cs);
   writeln(std.string.fromStringz(cs));
}
```

but it seems that "immutable" is a lie in that case.


More information about the Digitalmars-d-learn mailing list