converting D's string to use with C API with unicode
Jack
jckj33 at gmail.com
Sun Dec 6 20:53:10 UTC 2020
On Sunday, 6 December 2020 at 04:41:56 UTC, Виталий Фадеев wrote:
> On Saturday, 5 December 2020 at 19:51:14 UTC, Jack wrote:
>> So in D I have a struct like this:
>>
>>>struct ProcessResult
>>>{
>>> string[] output;
>>> bool ok;
>>>}
>>
>> in order to use output from C WINAPI with unicode, I need to
>> convert each string to wchar* so that i can acess it from C
>> with wchar_t*. Is that right or am I missing anything?
>>
>>
>>>struct ProcessResult
>>>{
>>> string[] output;
>>> bool ok;
>>>
>>> C_ProcessResult toCResult()
>>> {
>>> auto r = C_ProcessResult();
>>> r.ok = this.ok; // just copy, no conversion needed
>>> foreach(s; this.output)
>>> r.output ~= cast(wchar*)s.ptr;
>>> return r;
>>> }
>>>}
>>
>>>version(Windows) extern(C) export
>>>struct C_ProcessResult
>>>{
>>> wchar*[] output;
>>> bool ok;
>>>}
>
> Drawing string via WinAPI. As example.
>
> // UTF-16. wchar*
> wstring ws = "Abc"w;
> ExtTextOutW( hdc, x, y, 0, &clipRect, cast( LPCWSTR ) ws.ptr,
> cast( uint ) ws.length, NULL );
>
> // UTF-8. char*
> string s = "Abc";
> import std.utf : toUTF16;
> string ws = s.toUTF16;
> ExtTextOutW( hdc, x, y, 0, &clipRect, cast( LPCWSTR ) ws.ptr,
> cast( uint ) ws.length, NULL );
>
> // UTF-32. dchar*
> dstring ds = "Abc"d;
> import std.utf : toUTF16;
> string ws = ds.toUTF16;
> ExtTextOutW( hdc, x, y, 0, &clipRect, cast( LPCWSTR ) ws.ptr,
> cast( uint ) ws.length, NULL );
>
> One char.
> // UTF-16. wchar
> wchar wc = 'A';
> ExtTextOutW( hdc, x, y, 0, &clipRect, cast( LPCWSTR ) &wc, 1,
> NULL );
>
> // UTF-32. dchar
> dchar dc = 'A';
> import std.utf : encode;
> wchar[ 2 ] ws;
> auto l = encode( ws, dc );
> ExtTextOutW( hdc, x, y, 0, &clipRect, cast( LPCWSTR ) &ws.ptr,
> cast( uint ) l, NULL );
>
> //
> // Font API
> string face = "Arial";
> LOGFONT lf;
> import std.utf : toUTF16;
> lf.lfFaceName[ 0 .. face.length ] = face.toUTF16;
> HFONT hfont = CreateFontIndirect( &lf );
>
> // Common case
> LPWSTR toLPWSTR( string s ) nothrow // wchar_t*. UTF-16
> {
> import std.utf : toUTFz, toUTF16z, UTFException;
> try { return toUTFz!( LPWSTR )( s );
> }
> catch ( UTFException e ) { return cast( LPWSTR )
> "ERR"w.ptr; }
> catch ( Exception e ) { return cast( LPWSTR )
> "ERR"w.ptr; }
> }
didn't know about toUTFz!( LPWSTR ), I'll save everything else
for futher reference, I'll be using WINAPI for a while. Thanks
> alias toLPWSTR toPWSTR;
> alias toLPWSTR toLPOLESTR;
> alias toLPWSTR toPOLESTR;
that's interesting, I didn't about using multiples alias.
> // WinAPI
> string windowName = "Abc";
> HWND hwnd =
> CreateWindowEx(
> ...
> windowName.toLPWSTR,
> ...
> );
More information about the Digitalmars-d-learn
mailing list