VBA在OSX上遇到strerror / strncpy问题

问题描述 投票:1回答:1

每次使用此代码时,我的Excel电子表格都会锁定。通常这意味着某种声明或调用错误(无知的错误),但我还没有确定它。

此示例VBA函数SystemErrorText应返回errno 2:未找到文件的系统错误消息的文本。它没有:它永远不会从调用strncpy返回

'char *strerror(int errnum);
Public Declare Function osx_strErrorlp Lib "libc.dylib" Alias "strerror" _
    (ByVal errnum As Long) As Long

'char *strncpy(char * restrict dst, const char * restrict src, size_t len);
Public Declare Function osx_strncpy Lib "libc.dylib" Alias "strncpy" _
    (ByVal strDestination As String, ByVal strSource As String, destlen As Long) As Long

Public Function SystemErrorText() As String
Dim ErrorText As String
Dim nLen As Long
Dim longpointer As Long
Dim lngptr2 As Long

longpointer = osx_strErrorlp(2)
ErrorText = String(256, Chr(0))
nLen = 255
lngptr2 = osx_strncpy(ErrorText, longpointer, nLen)
SystemErrorText = ErrorText

End Function

谁能看到我做错了什么?我从strerror得到一个指针,我认为这是正确的(也许错误在那里?),但我不确定这是否重要:我只是试图从该位置复制一些字节。

我不能保证我作为注释包含的c声明对OS X有效:我已经给了它们,但我没有一个源保证它们对OS X有效。我使用的是32位版本的Excel for Mac:指针是32位,长度也是如此。与Windows版本的Excel不同,Mac版本无法防止对库函数调用时的堆栈错误:它只是崩溃。由于某种原因,err.LastDLLerror没有连接到errno(不是这个例子很重要)。

vba macos declaration libc excel-vba-mac
1个回答
0
投票

该声明的使用方式有误:

Public Declare Function osx_strncpy Lib "libc.dylib" Alias "strncpy" _
    (ByVal strDestination As String, ByVal strSource As String, destlen As Long) As Long

“strSource”被声明为ByVal字符串。这意味着指向空终止字符串的指针将传递给libc函数(好)。但这也意味着VBA代码将接受并需要BSTR参数(坏)。

调用函数的位置:

lngptr2 = osx_strncpy(ErrorText, longpointer, nLen)

... longpointer值首先被隐式转换为BSTR。然后将该bSTR的值(包含指针值的文本表示的空终止字符串的地址)传递给libc函数。

因此strncpy是从本地临时内存区域复制到目标,而不是从错误字符串复制到目标。为什么这会导致Excel崩溃是未知的:在相同的情况下,strlcpy不会崩溃。但这并不重要:即使确实有效,也不是想要的。

请注意,声明不是“错误的”,它可以正常工作

text1 = "A"
text2 = String(2,chr(0))
osx_strncpy(text2, text1, Len(text1))

- 这不是想要的东西。要求是接受指针值的函数:

Public Declare Function osx_strncpy_lp Lib "libc.dylib" Alias "strncpy" _
    (ByVal strDestination As String, ByVal strSource_lp As Long, destlen As Long) As Long

你甚至可以通过声明一个字符串对象,然后用你想要使用的指针值覆盖它的内部值来使原始声明工作。但是如果你这样做,你可以使用VBA赋值语句来复制kludged字符串对象

© www.soinside.com 2019 - 2024. All rights reserved.