将const wchar_t *转换为const char *

时间:2011-11-09 02:33:43

标签: windows visual-c++

我正在尝试使用GetHostByName()这需要一个const char *。我的URL在一个成本为wchar_t *格式的变量中。如何转换它以便GetHostByName可以使用它?代码。

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 *”类型的参数不兼容

4 个答案:

答案 0 :(得分:4)

我喜欢使用wcstombs(),因为它很容易使用。

试试这个样本:

char *str = new char[4046];
wchar_t array[] = L"Hello World";
wcstombs(str, array, 12);
std::cout << str;

这是你必须将wchar_t转换为char *。

的方法

修改

代码中的更改:

char* addr = new char[4046];
wcstombs(wsURL, addr, wsURL.size());
pHostEnt = gethostbyname(addr);

答案 1 :(得分:1)

这似乎有效。欢迎评论。

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);

答案 2 :(得分:0)

WideCharToMultiByte是Win32 API调用,它在一天结束时执行此操作,但根据您使用的框架(MFC,WTL等),可能有更好的方法。

答案 3 :(得分:0)

    /***** This code is well done *****/

    #include...
    #include...

    int wmain(int argc, wchar_t *argv[])
    {
         ...
         ...
         char *path = new char[255];
         wcstombs(path, argv[2], 255);
         IplImage *img; 
   if (img = cvLoadImage (path, 1))
         {
             Mat input_img = Mat (img);
             imshow ("haha",input_img);
             waitKey(0);
         }
         ...
         ...
         //wcout<<endl<<argv[2];
    }