Conversion of char and wchar in Windows

Source: Internet
Author: User

I have just encapsulated a C method. The most common problem is the conversion of char and wchar. I found some information:

 

1. Define the macro in the header file;

# Define Unicode # DEFINE _ Unicode
2. Convert Char to wchar

Const char * pfilepathname = "C: \ AA. dll ";

Int nlen = strlen (pfilepathname) + 1;

Int nwlen = multibytetowidechar (cp_acp, 0, pfilepathname, nlen, null, 0 );
Tchar lpszfile [256];

Multibytetowidechar (cp_acp, 0, pfilepathname, nlen, lpszfile, nwlen );
3. Convert wchar to Char

Char * pfilepathname;

Tchar lpszfile [256];

_ Tcscpy (lpszfile, _ T ("C: \ AA. dll "));
Int nlen = wcslen (wstr) + 1;

Widechartomultibyte (cp_acp, 0, lpszfile, nlen, pfilepathname, 2 * nlen, null, null );

 

A complete example (ws2_32.lib)

1. # include <windows. h> 2. # include <stdio. h> 3. 4. // function: chartowchar 5. // purpose: Char to wchar, wchar_t, lpwstr etc 6. void chartowchar (const char * CHR, wchar_t * wchar, int size) 7. {8. multibytetowidechar (cp_acp, 0, CHR, 9. strlen (CHR) + 1, wchar, size/sizeof (wchar [0]); 10 .} 11. 12. // function: wchartochar 13. // purpose: wchar, wchar_t, lpwstr to Char 14. void wchartochar (const wchar_t * wchar, char * CHR, int length) 15. {16. widechartomultibyte (cp_acp, 0, wchar,-1, 17. CHR, length, null, null); 18 .} 19. optional int main (void) 21. {22. char CHR [128]; 23. wchar_t * wchar = l "Chen hongqin"; 24. 25. 26. // wchar_t to Char 27. wchartochar (wchar, CHR, sizeof (CHR); 28. printf ("char is % s \ n", CHR); 29. 30. // Char to wchar_t 31. wchar = (wchar_t *) malloc (sizeof (wchar_t) * 64); 32. chartowchar (CHR, wchar, sizeof (wchar_t) * 64); 33. 34. wprintf_s (L "% s \ n", wchar); // 35. getchar (); 36. 37. return 0; 38 .}

Another macro:

#include "atlconv.h" void func() {  USES_CONVERSION; char *test = "i am a sucker";  WCHAR *conv = A2W(strPic1) ; }

  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.