【发布时间】:2015-01-14 10:40:13
【问题描述】:
我有一个 DLL,其函数声明如下:
char * __declspec(dllexport) WINAPI test(int x);
我想在 Access VBA 中这样调用它:
Private Declare Function "test" Lib "MyDLL.dll"(ByVal x As Long) As String
Sub MySub
Dim s As String
s = test(1)
End Sub
根据谷歌上的文章,我在DLL中写了一个函数:
BSTR CStrToVBStr(char *str)
{
int wslen = MultiByteToWideChar(CP_ACP, 0, str, lstrlen(str), 0, 0);
BSTR bstr = SysAllocStringLen(0, wslen);
MultiByteToWideChar(CP_ACP, 0, str, strlen(str), bstr, wslen);
return bstr;
}
在调用 test() 之后,s 显然包含 Unicode 字符。也就是说,一个 char * "test" 返回到 VBA 使得 Mid(s, 1, 1) = "t", Mid(s, 2, 1) = Chr(0), Mid(s, 3, 1) = "e" 等。我决定跳过转换为 Unicode 并将 CstrToVBStr 写为
BSTR CStrToVBStr(char *str)
{
return SysAllocString(str);
}
并忽略了 SysAllocString 采用 OLECHAR * 而不是 char * 参数的警告。 返回的字符串现在看起来不错,但包含空字符终止符,所以如果 char * 是“test”,那么在 VBA 中 len(s) = 5 和 Right(s,1) = Chr(0)。
什么是做我正在做的事情的正确方法?我看到的所有示例都是关于 char * 作为参数,而不是返回值。我可以将 test() 更改为
void __declspec(dllexport) WINAPI test(int x, char *result);
但我想知道我正在尝试做的事情是否可行。
我在 Windows 7(64 位)上使用 Access 2007。
【问题讨论】: