【问题标题】:C++ Convert wchar_t to char*C++ 将 wchar_t 转换为 char*
【发布时间】:2018-01-15 18:45:42
【问题描述】:

我的代码有问题。

我要做的是动态获取可执行路径,然后将其分配给char* n_argv 数组。我确实已经尝试了一段时间,但决定在这里问。抱歉,如果这是一个不恰当的问题。

int main (int argc, char** argv){

    char szPathToExe[MAX_PATH];
    GetModuleFileNameA(NULL, szPathToExe, MAX_PATH);

    std::string path(szPathToExe);
    path.append("other_argument");
    char *n_argv = path.c_str();

   argv = n_argv;


}

关于如何解决这个问题的任何想法?提前谢谢!

【问题讨论】:

  • 只需将wchar_t const * 用于n_argv 数组(注意"other_argument" 不能分配给char *)。
  • 使用GetModuleFileNameA 获取字符版本。
  • 正如@manni66 所说,使用GetModuleFileNameA,但也要考虑到这会将路径名中的任何Unicode 字符转换为基于代码页的字符。这是你想做的吗?也许您应该在项目选项中选择它时始终使用 Unicode。
  • 在 windows 代码中,您通常应该坚持使用 wchar_t 而不是转换为 char。如果您需要 char 则使用 gkpln3 answer中的函数
  • n_argv 不是数组。它是一个指针。

标签: c++


【解决方案1】:

使用wcstombswcstombs_s

https://msdn.microsoft.com/en-us/library/5d7tc9zw.aspx

size_t wcstombs(  
   char *mbstr,  
   const wchar_t *wcstr,  
   size_t count   
);  
size_t _wcstombs_l(  
   char *mbstr,  
   const wchar_t *wcstr,  
   size_t count,  
   _locale_t locale  
);

【讨论】:

    【解决方案2】:

    这是一个基于this 帖子的简单实现,您可以使用:

    #include <windows.h>    
    
    auto wide_to_char(const WCHAR* source) {
        const auto wide_char_file_path_length = wcslen(source);
        auto destination_buffer = std::make_unique<char[]>(wide_char_file_path_length + 1);
    
        auto array_index = 0;
        while (source[array_index] != '\0') {
            destination_buffer.get()[array_index]= static_cast<CHAR>(source[array_index]);
            array_index++;
        }
    
        destination_buffer.get()[array_index] = '\0';
        return destination_buffer;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 2015-08-05
      • 2015-09-25
      • 2011-03-14
      相关资源
      最近更新 更多