I try to convert strings which may contain UTF-8 characters to Windows 1252 (German) encoding with this function:
Code: Select all
FUNCTION ConvertFromCodePageToCodePage(cString AS STRING, dwFrom AS DWORD, dwTo AS DWORD) AS STRING
LOCAL pUStr AS PTR
LOCAL pBuffer, pBuf1, pBuf2 AS PTR
LOCAL nLen, nLenRes, nULen, nULenRes AS LONG
// Convert VO string from dynamic memory to fixed memory
nLen := LONG(SLen(cString))
pBuffer := MemAlloc(DWORD(nLen))
pBuf1 := pBuffer
IF pBuffer == NULL_PTR
BREAK "MemAlloc error"
ENDIF
MemCopyString(pBuffer,cString,DWORD(nLen))
// Determine length of Unicode string
// And allocate enough space to hold it
nULen := MultiByteToWideChar(dwFrom,0,pBuffer,nLen,NULL_PTR, 0)
IF nULen == 0
BREAK "MultiByteToWideChar GetLen error"
ENDIF
IF pBuffer <> pBuf1
BREAK "pBuffer modified"
ENDIF
pUStr := SysAllocStringLen(NULL_PTR,DWORD(nULen))
IF pUStr == NULL_PTR
BREAK "SysAllocStringLen error"
ENDIF
// Convert Fixed memory Ansi string to Fixed memory Unicode string
nULenRes := MultiByteToWideChar(dwFrom,0,pBuffer,nLen,pUStr,nULen)
IF nULen <> nULenRes
BREAK "MultiByteToWideChar Copy Len<>"
ENDIF
// Now determine size needed for ANSI string
nLen := WideCharToMultiByte(dwTo,0,pUStr,nULen,NULL_PTR,0, NULL,NULL)
// Allocate Fixed memory buffer to hold the UTF8 string
pBuffer := MemRealloc(pBuffer, DWORD(nLen+1))
IF pBuffer == NULL_PTR
BREAK "MemRealloc error"
ENDIF
pBuf2 := pBuffer
// Convert Unicode to Ansi
nLenRes := WideCharToMultiByte(dwTo,0,pUStr,nULen,pBuffer,nLen ,NULL,NULL)
IF nLen <> nLenRes
BREAK "WideCharToMultiByte Len<>"
ENDIF
// Convert fixed memory buffer to dynamic memory string
cString := Mem2String(pBuffer,DWORD(nLen))
IF pBuffer <> pBuf2
BREAK "pBuffer 2 modified"
ENDIF
// Release fixed memory buffer
IF MemFree(pBuffer) <> 0
BREAK "MemFree error: " + cString // <------ here it breaks
ENDIF
// Release the Unicode String
SysFreeString(pUStr)
RETURN cString
Without all the test IF's it failed after some calls with an 5333 error. It works for some calls and fails with others. The string which creates the error is about 400 characters long and contains a handful of UTF-8 characters.
I absolutely don't understand what's going on. pBuffer is saved and compared before freeing, so it's the same.
Debugging works regarding breakpoints, but I am not able to look at any variable, neither by hovering nor by ctrl-x. Mostly it shows empty, sometimes a result from a previous assignment to some other variable in the code, so unusable.
VO2740, Win10 Enterprise 20H2, Windows Information Protection enabled (Company policy)
Any ideas?
BR Kurt