如何在D 2.0中使用wchar **初始化wstring []

问题描述

| 在C ++中,我可以使用wchar_t **初始化vector ,例如以下示例:
#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);
    }
}
但是,有没有一种方法可以在D 2.0中用wchar **初始化wstring []? 我可以通过以下方式将wchar **的内容添加到wstring []中:
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);
    }
}
但是,我想找到一种更清洁,更简单的方式,例如C ++版本。 (性能不是问题)     

解决方法

这是使用切片的更简单版本:
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);
    }
}
另一个选择是使用
void main(string[] args)
并根据需要转换为args wstring。     ,您可以使用
void main(wstring[] args){
//...
}
使命令行参数更容易 编辑:并且在D中获得char指针的唯一原因是,如果直接使用C函数,而90%的时间则不需要(或将其抽象掉)