vba PtrSafe函数类型不匹配

时间:2016-12-08 15:03:28

标签: vba excel-vba native declare type-mismatch

我将声明更改为PtrSafe,现在它在类型不匹配方面失败了。 我改变了有问题的参数,删除了StrPtr和VarPtr,它仍然给我一个类型不匹配。

以下代码(用于将unicode16字符串转换为UTF8字节数组)失败。我必须将声明更改为PtrSafe,否则声明代码保持红色。添加PtrSafe后,我现在得到一个类型不匹配,告诉我错误在哪里。

我更改了类型,因此它们现在适合调用代码,(通过删除编译器标记的StrPtr和ArrPtr作为不匹配的罪魁祸首),现在得到一般的Type Mismatch消息。我需要做什么?!

这是我的代码,以及我得到的错误:

''' WinApi function that maps a UTF-16 (wide character) string to a new character string
Private Declare PtrSafe Function WideCharToMultiByte Lib "kernel64" ( _
    ByVal CodePage As Long, _
    ByVal dwFlags As Long, _
    ByVal lpWideCharStr As Long, _
    ByVal cchWideChar As Long, _
    ByVal lpMultiByteStr As Long, _
    ByVal cbMultiByte As Long, _
    ByVal lpDefaultChar As Long, _
    ByVal lpUsedDefaultChar As Long) As Long

Private Const CP_UTF8 = 65001 ' CodePage constant for UTF-8


''' Return byte array with VBA "Unicode" string encoded in UTF-8
Public Function Utf8BytesFromString(strInput As String) As Byte()
    Dim nBytes As Long
    Dim abBuffer() As Byte
    ' Get length in bytes *including* terminating null
    nBytes = WideCharToMultiByte(CP_UTF8, 0&, ByVal strInput, -1, vbNull, 0&, 0&, 0&) 
' Error!  This gives unspecified Type Mismatch
' whereas before when was defined as 
' nBytes = WideCharToMultiByte(CP_UTF8, 0&, ByVal StrPtr(strInput), -1, vbNull, 0&, 0&, 0&)
' it gave a specified Type Mismatch, marking in blue the StrPtr 

' We don't want the terminating null in our byte array, so ask for `nBytes-1` bytes
    ReDim abBuffer(nBytes - 2)  ' NB ReDim with one less byte than you need
    nBytes = WideCharToMultiByte(CP_UTF8, 0&, ByVal strInput, -1, ByVal abBuffer(0), nBytes - 1, 0&, 0&) 
    Utf8BytesFromString = abBuffer
    ' this too failed with Type Mismatch on StrPtr and VarPtr when defined as 
    ' nBytes = WideCharToMultiByte(CP_UTF8, 0&, ByVal StrPtr(strInput), -1, ByVal VarPtr(abBuffer(0)), nBytes - 1, 0&, 0&)

End Function

Public Sub Tryit()
    Dim sht as WorkSheet
    Dim bytArr() As Byte
    Dim str as string
    Set sht = Sheets(1)
    str = sht.Cells(1,1) ' a string with gibberish imported incorrectly from a UTF8 file
    bytArr = Utf8BytesFromString(str) 
End Sub

原始代码取自a post on the DI Managment website

这个问题与a similar question, here之间的差异(据说有一个答案,但一个不起作用,并且没有解释为什么或它们是什么):

一个。我在标题和问题中指出该问题也是一个普遍的问题,PtrSafe和64位。

湾我给出了代码的来源。

℃。我只更改了POINTERS的声明和调用代码,而不更改直接参数。我可以放心地认为这就是他们的答案仍然失败的原因。任何回答我的问题(并让它工作)的人也会展示如何以及需要改变什么,而在另一个问题中,你需要做的就是解决代码,并让程序员猜测为什么以及如何处理类似的代码(例如在找到此代码的线程上找到的内容。

0 个答案:

没有答案