gpt4 book ai didi

c++ - 将 WinMain(或 wWinMain)参数传递给普通的 main

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:08 25 4
gpt4 key购买 nike

如果您尝试将构建类型从 Console (/SUBSYSTEM:CONSOLE) 更改为 Windows (/SUBSYSTEM:WINDOWS),您将收到一个错误提示该条目缺少 WinMain 点:

MSVCRT.lib(crtexew.obj) : error LNK2001: unresolved external symbol _WinMain@16

我认为解决这个问题的最好方法是从 WinMain 调用您的普通 int main(int, char**):

#ifdef _WINDOWS_
INT WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR lpCmdLine, INT nCmdShow)
{
return main(0, NULL);
}
#endif

问题是 ImageMagick 正在使用控制台参数(我也计划在未来使用它们):

Segmentation fault imagemagick init

因此传递 NULL0 可能不是一个好主意。如何将 WinMain 参数转换为 main 参数?

最佳答案

一种方法是使用 CommandLineToArgvW()解析 GetCommandLineW() 的结果转换为 argv 样式的 UTF-16 编码字符串数组,然后使用 WideCharToMultiByte()将它们转换为 ANSI 字符串,这样您就可以将它们传递给 main()(假设您不能改用 wmain())。

例如:

int w_argc = 0;
LPWSTR* w_argv = CommandLineToArgvW(GetCommandLineW(), &w_argc);
if (w_argv)
{
char** my_argv = new char*[w_argc];
int my_argc = 0;

for (int i = 0; i < w_argc; ++i)
{
int w_len = lstrlenW(w_argv[i]);
int len = WideCharToMultiByte(CP_ACP, 0, w_argv[i], w_len, NULL, 0, NULL, NULL);
my_argv[my_argc] = new char[len+1];
WideCharToMultiByte(CP_ACP, 0, wargv[i], w_len, my_argv[my_argc], len+1, NULL, NULL);
++my_argc;
}

main(my_argc, my_argv);

for (int i = 0; i < my_argc; ++i)
delete[] my_argv[i];
delete[] my_argv;

LocalFree(w_argv);
}

或者:

int w_argc = 0;
LPWSTR* w_argv = CommandLineToArgvW(GetCommandLineW(), &w_argc);
if (w_argv)
{
std vector<std::string> my_argv_buf;
my_argv.reserve(w_argc);

for (int i = 0; i < w_argc; ++i)
{
int w_len = lstrlenW(w_argv[i]);
int len = WideCharToMultiByte(CP_ACP, 0, w_argv[i], w_len, NULL, 0, NULL, NULL);
std::string s;
s.resize(len);
WideCharToMultiByte(CP_ACP, 0, wargv[i], w_len, &s[0], len, NULL, NULL);
my_argv_buf.push_back(s);
}

std vector<char*> my_argv;
my_argv.reserve(my_argv_buf.size());
for (std vector<std::string>::iterator i = my_argv_buf.begin(); i != my_argv_buf.end(); ++i)
my_argv.push_back(i->c_str());

main(my_argv.size(), &my_argv[0]);

LocalFree(w_argv);
}

关于c++ - 将 WinMain(或 wWinMain)参数传递给普通的 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27363851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com