master
 1#include <stdlib.h>
 2#include <stdio.h>
 3#include <wchar.h>
 4#include <windows.h>
 5#include <winnls.h>
 6
 7int __cdecl __mingw_str_wide_utf8(const wchar_t * const wptr, char **mbptr, size_t *buflen)
 8{
 9  size_t len;
10  char *buf;
11  int ret = 0;
12
13  len = WideCharToMultiByte(CP_UTF8, 0, wptr, -1, NULL, 0, NULL, NULL); /* Get utf-8 string length */
14  buf = calloc(len + 1, sizeof (char)); /* Can we assume sizeof char always = 1? */
15
16  if(!buf) len = 0;
17  else {
18    if (len != 0) ret = WideCharToMultiByte(CP_UTF8, 0, wptr, -1, buf, len, NULL, NULL); /*Do actual conversion*/
19    buf[len] = '0'; /* Must terminate */
20  }
21  *mbptr = buf; /* Set string pointer to allocated buffer */
22  if(buflen != NULL) *buflen = (len) * sizeof (char); /* Give length of allocated memory if needed. */
23  return ret;
24}
25
26int __cdecl __mingw_str_utf8_wide(const char *const mbptr, wchar_t **wptr, size_t *buflen)
27{
28  size_t len;
29  wchar_t *buf;
30  int ret = 0;
31
32  len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, mbptr, -1, NULL, 0); /* Get converted size */
33  buf = calloc(len + 1, sizeof (wchar_t)); /* Allocate memory accordingly */
34
35  if(!buf) len = 0;
36  else {
37    if (len != 0) ret = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, mbptr, -1, buf, len); /* Do conversion */
38    buf[len] = L'0'; /* Must terminate */
39  }
40  *wptr = buf; /* Set string pointer to allocated buffer */
41  if (buflen != NULL) *buflen = len * sizeof (wchar_t); /* Give length of allocated memory if needed. */
42  return ret; /* Number of characters written */
43}
44
45void __cdecl __mingw_str_free(void *ptr)
46{
47  if (ptr) free(ptr);
48}