将 const wchar_t* 转换为 const char* [英] Convert const wchar_t* to const char*
本文介绍了将 const wchar_t* 转换为 const char*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 GetHostByName() 这需要一个 const char*.我的 URL 位于成本 wchar_t* 格式的变量中.如何转换它以便 GetHostByName 可以使用它?代码.
I am trying to use GetHostByName() this requires a const char*. I have my URL in a variable that is in a cost wchar_t* format. How can I convert this so that GetHostByName may use it? The code.
BSTR bstr;
pBrowser->get_LocationURL(&bstr);
std::wstring wsURL;
wsURL = bstr;
size_t DSlashLoc = wsURL.find(L"://");
if (DSlashLoc != wsURL.npos)
{
wsURL.erase(wsURL.begin(), wsURL.begin() + DSlashLoc + 3);
}
DSlashLoc = wsURL.find(L"www.");
if (DSlashLoc == 0)
{
wsURL.erase(wsURL.begin(), wsURL.begin() + 4);
}
DSlashLoc = wsURL.find(L"/");
if (DSlashLoc != wsURL.npos)
{
wsURL.erase(DSlashLoc);
}
wprintf(L"\n Current Website URL: %s\n\n", wsURL.c_str());
HOSTENT *pHostEnt;
int **ppaddr;
SOCKADDR_IN sockAddr;
char* addr;
pHostEnt = gethostbyname(wsURL.c_str());
ppaddr = (int**)pHostEnt->h_addr_list;
sockAddr.sin_addr.s_addr = **ppaddr;
addr = inet_ntoa(sockAddr.sin_addr);
printf("\n Current Website IP:%s", addr);
int length = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, NULL, 0, NULL, NULL);
std::string LogURL(length+1, 0);
int result = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, &LogURL[0],length+1, NULL, NULL);
myfile << "\n Current Website URL:" << LogURL;
myfile << "\n Current Website IP:"<< addr;
这是我得到的错误.IntelliSense:const wchar_t *"类型的参数与const char *"类型的参数不兼容
This is the error I am getting. IntelliSense:argument of type "const wchar_t *" is incompatible with parameter of type "const char *"
推荐答案
这似乎有效.欢迎评论.
This seems to work. Comments welcome.
int Newlength = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, NULL, 0, NULL, NULL);
std::string NewLogURL(Newlength+1, 0);
int Newresult = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, &NewLogURL[0],Newlength+1, NULL, NULL);
HOSTENT *pHostEnt;
int **ppaddr;
SOCKADDR_IN sockAddr;
char* addr;
pHostEnt = gethostbyname(NewLogURL.c_str());
ppaddr = (int**)pHostEnt->h_addr_list;
sockAddr.sin_addr.s_addr = **ppaddr;
addr = inet_ntoa(sockAddr.sin_addr);
printf("\n Current Website IP:%s", addr);
这篇关于将 const wchar_t* 转换为 const char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文