VBA调用相同的C ++ DLL返回不同的结果 [英] VBA call same C++ dll return different results

查看:172
本文介绍了VBA调用相同的C ++ DLL返回不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试dll函数读取一个字符串并显示它:

  int _stdcall test(LPSTR myString){
MessageBoxA(NULL,(LPCSTR)myString,test,MB_OK);
return 0;}

excel VBA声明是

 声明函数test Libtest.dll(ByVal text As String)As Long 

有一个子调用该函数。它读取一个值为abcde的excel单元格,并能够显示正确的结果。子代码是:

  sub testCode()
test(cells(1,1).value)
end sub

然而,当使用excel公式调用dll函数时 = test (A1),消息框只显示字符串的第一个字符a。



我花了整个周末阅读BSTR等,仍然无法解决这个问题。这里发生了什么?

解决方案

将导入的函数声明为私有:

 私有声明函数test_internal Libtest.dll别名test(ByVal text As String)As Long 

并为Excel创建一个包装函数:

 公共函数测试(ByVal text As String)As Long 
Test = test_internal(text)
End Functin

因为显然,当调用 Declare d API时,VB(A)使用当前系统代码页将字符串参数转换为ASCII, Excel引擎没有。



在附注中,您还可能需要删除括号


I have a test dll function that reads a string and display it:

int _stdcall test(LPSTR myString) {
MessageBoxA(NULL, (LPCSTR)myString, "test", MB_OK);
return 0;}

The excel VBA declaration is

Declare Function test Lib "test.dll" (ByVal text As String) As Long

There is a sub that calls the function. It reads an excel cell with value as "abcde" and is able to display a correct result. The sub code is:

sub testCode()
    test (cells(1,1).value)
end sub

However when call the dll function using excel formula =test(A1), the message box only display the first char "a" of the string.

I had spent entire weekend reading BSTR, etc, still not be able to solve this. What is going on here?

解决方案

Declare your imported function as private:

Private Declare Function test_internal Lib "test.dll" Alias "test" (ByVal text As String) As Long

and create a wrapper function for Excel to use:

Public Function Test (ByVal text As String) As Long
  Test = test_internal(text)
End Functin

Because apparently, while VB(A) converts string arguments to ASCII using the current system codepage when calling to Declared APIs, the Excel engine does not.

On a side note, you also might want to remove parentheses.

这篇关于VBA调用相同的C ++ DLL返回不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆