写了一个函数,感觉有些累赘?
字符串采用UNICODE,写了一个函数获取本机的名称与IP,由于gethostname函数只能采用ANSI字符串,所以在使用过程中进行了转换,来回折腾了一下,感觉有些累赘;能否优化一下?
- C/C++ code
UINT getLocalName(wchar_t *pName,wchar_t *pIp) { WSADATA wsaData; DWORD len; BSTR strptr; char hostname[64]; char ipString[16]; struct hostent *h; WSAStartup(MAKEWORD(2,0), &wsaData); gethostname(hostname,sizeof(hostname)); h=gethostbyname(hostname); len=MultiByteToWideChar(CP_ACP,0,hostname,-1,0,0); strptr=SysAllocStringLen(0,len); MultiByteToWideChar(CP_ACP,0,hostname,-1,strptr,len); wcscpy(pName,strptr); SysFreeString(strptr); strcpy(ipString, inet_ntoa(*((struct in_addr *)h->h_addr))); len=MultiByteToWideChar(CP_ACP,0,ipString,-1,0,0); strptr=SysAllocStringLen(0,len); MultiByteToWideChar(CP_ACP,0,ipString,-1,strptr,len); wcscpy(pIp,strptr); SysFreeString(strptr); WSACleanup(); return(NOERROR); }
[解决办法]
好像没的简化,要不就是用W2A替换你Unicode转换的函数