Search code examples
d

How to initialize wstring[] with wchar** in D 2.0


In C++, I can initialize a vector<wstring> with a wchar_t** like in this example:

#include <windows.h>
#include <string>
#include <vector>
#include <cwchar>
using namespace std;

int main() {
    int argc;
    wchar_t** const args = CommandLineToArgvW(GetCommandLineW(), &argc);
    if (args) {
        const vector<wstring> argv(args, args + argc);
        LocalFree(args);
    }
}

However, is there a way to initialize a wstring[] with a wchar** in D 2.0?

I can add the contents of the wchar** to the wstring[] this way:

import std.c.windows.windows;
import std.c.wcharh;

extern(Windows) {
    wchar* GetCommandLineW();
    wchar** CommandLineToArgvW(wchar*, int*);
    void* LocalFree(void*);
}

void main() {
    int argc;
    wchar** args = CommandLineToArgvW(GetCommandLineW(), &argc);
    if (args) {
        wstring[] argv;
        for (size_t i = 0; i < argc; ++i) {
            wstring temp;
            const size_t len = wcslen(args[i]);
            for (size_t z = 0; z < len; ++z) {
                temp ~= args[i][z];
            }
            argv ~= temp;
        }
        LocalFree(args);
    }
}

But, I'd like to find a cleaner, simpler way like the C++ version. (Performance is not an concern)


Solution

  • Here is a simpler version using slices:

    import std.c.windows.windows;
    import std.c.wcharh;
    import std.conv;
    
    extern(Windows) {
        wchar* GetCommandLineW();
        wchar** CommandLineToArgvW(wchar*, int*);
        void* LocalFree(void*);
    }
    
    void main() {
        int argc;
        wchar** args = CommandLineToArgvW(GetCommandLineW(), &argc);
        if (args) {
            wstring[] argv = new wstring[argc];
            foreach (i, ref arg; argv)
                arg = to!wstring(args[i][0 .. wcslen(args[i])]);
            LocalFree(args);
        }
    }
    

    Another option would be to use void main(string[] args) and convert to args wstring if you really need.