【问题标题】:Call C function in DLL that returns char * from MS-Access VBA在从 MS-Access VBA 返回 char * 的 DLL 中调用 C 函数
【发布时间】: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。

【问题讨论】:

    标签: ms-access dll vba


    【解决方案1】:

    charinteger 相同。在 VBA 中,这意味着 long(因为 VBA 使用 16 位术语)。不涉及任何字符串。要将整数或字符转换为字符串,请使用chr(x)

    【讨论】:

    • 我返回的是一个 C 字符串(char *,即指向 char 的指针),而不是 char。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2018-11-16
    • 2018-11-14
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多