Interfacing C programs: Pass D string to C function
Jonathan M Davis
jmdavisProg at gmx.com
Fri Dec 13 01:17:41 PST 2013
On Friday, December 13, 2013 09:00:20 Dfr wrote:
> Hello
>
> I trying to write simple wrapper around pcre and have problem
> passing strings to it. As i understood, the best way is
> std.string.toStringZ.
>
> So, my code look like:
>
> string pattern = "....";
> pcre_compile2( toStringz(pattern), options, &errcode, &errmsg,
> &erroffset, cast(char*)null);
>
> This gives me error:
>
> Error: function pcre_compile2 (char*, int, int*, char**, int*,
> char*) is not callable using argument types (immutable(char)*,
> int, int*, char**, int*, char*)
>
> Any ideas for better way to do this task ?
The problem is that toStringz returns immutable(char)* (because string is
immutable(string)[]), and your function is taking char*. It will work to pass
the result of toStringz to a C function which takes const char* (since
immutable will implicitly convert to const), but immutable doesn't implicitly
convert to mutable, and casting immutable mutable is almost always a bad idea.
The easiest solution would be to use std.utf.toUTFz. e.g.
auto cstr = str.toUTFz!(char*)();
or you could do something like
auto cstr = str.dup.ptr;
In either case, what you're doing is allocating a new char[] which holds the
same elements as the original string and getting its ptr property so that you
have a char*.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list