Nul terminated CString analog for Windows wchar_t* (LPWSTR)?

Would a type for nul-terminated wide character buffers make sense for Windows? It seems like a number of Windows libs take a string like that. I don’t do Windows programming so I can’t tell how often it would actually come up, but CString is very handy in unix land!

Generally, you just convert to Vec<u16> at the last instant and pass that. See wide::ToWide and FromWide in wio.

So is checking for interior nuls / ensuring nul termination less of an issue on Windows? Or do you go via CString to handle those parts?

A lot of the APIs are sane enough to take a length; for those that aren’t, you can just ensure there is a NUL on the end during conversion. That doesn’t cover interior NULs, though I’m not sure how much of an issue that is in practice.

For interior nulls I’ll probably add a to_wide_null_checked method that checks for interior nulls and returns an Option.

So I’m hearing there’s no need / desire for a type that acts as “a static guarantee” for nul termination / absence of interior nuls as does CString. Is that because you would delay the conversion further on Windows because it’s u16 and so less easy to work with?

I actually recently (this weekend) uploaded my widestring library to crates.io which does exactly this. The library has WideString and WideCString types for working with windows wide strings. The WideString type is just a thin, string-like wrapper around Vec that performs the conversions to/from regular Rust strings. It doesn’t do any nul checking but is usually sufficient for a lot of the use cases. WideCString on the other hand, is nul-terminated and checks for interior nuls, just like CString, for the cases you need to worry about that.

In both cases, the types are intended to be used only to convert around the windows FFI, where output conversion is delayed until the last possible moment (or converted immediately into Rust strings on input).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.