Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

d

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)

like image 832
Shadow2531 Avatar asked May 25 '11 04:05

Shadow2531


2 Answers

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.

like image 109
Nekuromento Avatar answered Oct 13 '22 23:10

Nekuromento


you can use

void main(wstring[] args){
//...
}

to get the commandline arguments much easier

edit: and the only reason you'd get a char pointer in D is if you are using C functions directly while 90% of the time you shouldn't need to (or should abstract it away)

like image 21
ratchet freak Avatar answered Oct 13 '22 21:10

ratchet freak