c++ - 我可以检索包含非拉丁字符的路径吗?

标签 c++ winapi visual-c++ getmodulefilename

我调用GetModuleFileName函数,为了检索指定模块的完全限定路径,为了调用同一文件中的另一个 .exe,通过 Process::Start方法。

但是,当路径包含非拉丁字符(在我的例子中是希腊字符)时,无法调用 .exe。

有什么办法可以解决这个问题吗?

代码:

    TCHAR path[1000];
    GetModuleFileName(NULL, path, 1000) ; // Retrieves the fully qualified path for the file that
                                          // contains the specified module.

    PathRemoveFileSpec(path); // Removes the trailing file name and backslash from a path (TCHAR).

    CHAR mypath[1000];
    // Convert TCHAR to CHAR.
    wcstombs(mypath, path, wcslen(path) + 1);

    // Formatting the string: constructing a string by substituting computed values at various 
    // places in a constant string.
    CHAR mypath2[1000];
    sprintf_s(mypath2, "%s\\Client_JoypadCodesApplication.exe", mypath);

    String^ result;
    result = marshal_as<String^>(mypath2);

    Process::Start(result);

最佳答案

.NET 中的字符串以 UTF-16 编码。您正在调用 wcstombs() 这一事实意味着您的应用程序是针对 Unicode 编译的,并且 TCHAR 映射到 WCHAR,这是 Windows 用于 UTF 的-16。所以根本不需要调用 wcstombs()。检索路径并将其格式化为 UTF-16,然后将其编码为 UTF-16。完全停止使用 TCHAR(除非您需要为 Windows 9x/ME 编译):

WCHAR path[1000];
GetModuleFileNameW(NULL, path, 1000);

PathRemoveFileSpecW(path);

WCHAR mypath[1000];
swprintf_s(mypath, 1000, L"%s\\Client_JoypadCodesApplication.exe", path);

String^ result;
result = marshal_as<String^>(mypath);

Process::Start(result);

更好的选择是改用 native .NET 解决方案(未经测试):

String^ path = Path::DirectoryName(Application->StartupPath); // uses GetModuleFileName() internally
// or:
//String^ path = Path::DirectoryName(Process::GetCurrentProcess()->MainModule->FileName);

Process::Start(path + L"\\Client_JoypadCodesApplication.exe");

关于c++ - 我可以检索包含非拉丁字符的路径吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23695127/

相关文章:

c++ - UnitTest++创建cmd窗口,无法关闭

c++ - ReadFile() 读取的字节数少于其参数中指定的值

c++ - 从 C 中的函数返回 char 数组的首选方法

c++ - IFileOpenDialog 无法在 XP 中启动

c - 为什么同一个结构体的大小在x86和arm同版本gcc中计算出来的不一样?

visual-c++ - Windows 和控制台应用程序之间的区别

c++ - 按行解析和排序 csv 文件

c++ - R:xgboost源代码中的梯度步骤在哪里?

c++ - 在 Ubuntu 16.04 LTS 中为 OpenCV 使用 CodeLite IDE

c++ - 在对可执行文件大小没有严格限制的情况下,为什么在 Visual C++ 9 中更喜欢/Ob1 而不是/Ob2?