Skip to content

Instantly share code, notes, and snippets.

@koturn
Created October 9, 2025 16:44
Show Gist options
  • Save koturn/2a10ca15a27d873417aeeb27363bcf1f to your computer and use it in GitHub Desktop.
Save koturn/2a10ca15a27d873417aeeb27363bcf1f to your computer and use it in GitHub Desktop.
C文字列(UTF-8)からVBAの文字列(UTF-16)に変換する例
Private Declare PtrSafe Function lstrlenA Lib "kernel32" (ByVal lpString As LongPtr) As Long
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
ByRef Destination As Any, _
ByVal Source As LongPtr, _
ByVal Length As Long)
Public Function PtrToStringAnsi(ByVal pStr As LongPtr) As String
Dim nLen As Long
Dim s As String
If pStr = 0 Then Exit Function
nLen = lstrlenA(pStr)
If nLen = 0 Then Exit Function
s = String$(nLen, vbNullChar)
CopyMemory ByVal s, pStr, nLen
PtrToStringAnsi = s
End Function
Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function lstrlenA Lib "kernel32" (ByVal lpString As LongPtr) As Long
Private Declare PtrSafe Function MultiByteToWideChar Lib "kernel32" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByVal lpMultiByteStr As LongPtr, _
ByVal cbMultiByte As Long, _
ByVal lpWideCharStr As LongPtr, _
ByVal cchWideChar As Long) As Long
#Else
Private Declare Function lstrlenA Lib "kernel32" (ByVal lpString As Long) As Long
Private Declare Function MultiByteToWideChar Lib "kernel32" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByVal lpMultiByteStr As Long, _
ByVal cbMultiByte As Long, _
ByVal lpWideCharStr As Long, _
ByVal cchWideChar As Long) As Long
#End If
Private Const CP_UTF8 As Long = 65001
Private Const MB_ERR_INVALID_CHARS As Long = &H8&
Public Function PtrToStringUTF8(ByVal pUTF8 As LongPtr) As String
' Cのconst char* (UTF-8) を VBAのUnicode文字列に変換する
Dim cbUTF8 As Long
Dim cchWide As Long
Dim sWide As String
If pUTF8 = 0 Then Exit Function
' UTF-8のバイト数(NULL終端まで)を取得
cbUTF8 = lstrlenA(pUTF8)
If cbUTF8 = 0 Then Exit Function
' UTF-8 → UTF-16 (VBA String) へ変換
' まず必要なバッファサイズを取得
cchWide = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, pUTF8, cbUTF8, 0, 0)
If cchWide = 0 Then Exit Function
' バッファ確保
sWide = String$(cchWide, vbNullChar)
' 実際に変換
MultiByteToWideChar CP_UTF8, MB_ERR_INVALID_CHARS, pUTF8, cbUTF8, StrPtr(sWide), cchWide
PtrToStringUTF8 = sWide
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment