1 #include "utf8.h"
2 
3 
wstr_to_utf8(LPWSTR wstr,int len)4 char* wstr_to_utf8(LPWSTR wstr, int len)
5 {
6 	char *res = NULL;
7 
8 	int res_size = WideCharToMultiByte(CP_UTF8, 0, wstr, len, NULL, 0, NULL, NULL);
9 	if (res_size > 0) {
10 		// Note: WideCharToMultiByte doesn't null-terminate if real (ie. > 0) buffer length is passed
11 		res = malloc(len != - 1 ? res_size + 1 : res_size);
12 		if (res == NULL) { return NULL; }
13 
14 		if (WideCharToMultiByte(CP_UTF8, 0, wstr, len, res, res_size, NULL, NULL) == res_size) {
15 			if (len != -1) { res[res_size] = '\0'; }
16 		} else {
17 			free(res);
18 			return NULL;
19 		}
20 	}
21 
22 	return res;
23 }
24 
utf8_to_wstr(const char * str,int len)25 LPWSTR utf8_to_wstr(const char *str, int len)
26 {
27 	LPWSTR res = NULL;
28 
29 	int res_size = MultiByteToWideChar(CP_UTF8, 0, str, len, NULL, 0);
30 	if (res_size > 0) {
31 		// Note: MultiByteToWideChar doesn't null-terminate if real (ie. > 0) buffer length is passed
32 		res = malloc(len != - 1 ? res_size + 1 : res_size);
33 
34 		if (res == NULL) { return NULL; }
35 
36 		if (MultiByteToWideChar(CP_UTF8, 0, str, len, res, res_size) == res_size) {
37 			if (len != -1) { res[res_size] = L'\0'; }
38 		} else {
39 			free(res);
40 			return NULL;
41 		}
42 	}
43 
44 	return res;
45 }
46