简体   繁体   中英

D Style Arrays to C Style Arrays

I am creating a Window in D, and the CreateWindowA function requires pointers to characters, C character arrays basically.

How do I convert a D style array ( char[] ) to a C style array ( char* )?

The two functions to look at are normally std.string.toStringz and std.utf.toUTFz .

toStringz will convert string to immutable(char)* , which you can pass to a C function which takes const char* . If it can determine that the string is null-terminated (which usually is only the case for string literals, which have a null terminator one passed their end), then it won't allocate and will just use the string 's ptr property, but in most cases, it will allocate.

toUTFz will convert from any string type to any character pointer type. It's probably most frequently used for converting to const(wchar)* for Windows, since all of the W functions for Windows take UTF-16, but it can also be used to convert to char* - eg str.toUTFz!(char*)() . Like toStringz , it will try not to allocate if it can determine that it's unnecessary, but it's almost always necessary.

Now, for your particular case, you're trying to use one of the A functions in Windows. This is almost always a bad idea, and I would strongly advise against it. Use toUTFz to convert your string to const(wchar)* and pass that to CreateWindowW . AFAIK, the only advantage to the A functions is that they work with pre-Win2K. Everything else about them is worse. However, if for some reason, you insist on using the A functions, then you're going to have to use std.windows.charset.toMBSz , because the A functions don't take UTF-8 but rather the "Windows 8-bit character set," and toMBSz will convert the string to that format.

you grab the ptr field of the D array. and the length field to grab the length

however if you need a C-style string then you need the toStringz method that will add the null terminator and return the pointer to the first char. k eep a reference to it if the api doesn't create it's own copy to operate on to avoid dangling pointers by GC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM