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; }
}
alias toLPWSTR toPWSTR;
alias toLPWSTR toLPOLESTR;
alias toLPWSTR toPOLESTR;

// WinAPI
string windowName = "Abc";
HWND hwnd =
    CreateWindowEx(
        ...
        windowName.toLPWSTR,
        ...
    );


Reply via email to