【发布时间】:2015-01-06 03:54:37
【问题描述】:
我正在寻找将 VB6 布尔变量传递给函数(用 C++ 编写,stdcall)的最安全的方法。
C++ 函数将使用此 VB6 变量设置结构的“bool”变量。
我曾尝试在 C++ 中这样声明它:
extern "C" __declspec(dllexport) int SetParameter( BOOL bErrorView)
{
DLL_sSettings nSet;
nSet.bErrorView =(bErrorView != FALSE);
int ret = stSetParameter(sizeof(DLL_sSettings), nSet);
return (ret);
}
stSetParameter 声明为
extern "C" int ST_COMDLL_API stSetParameter(int DataLen, DLL_sSettings Settings);
DLL_sSetting 声明为
typedef struct
{
bool bErrorView; // true: Show
// false: Don't show
(...)
} DLL_sSettings;
但是,我无法让它工作。
我在 VB6 中使用
调用它Private Declare Function SetParameter Lib "MyDLL.dll" Alias "_SetParameter@4" (ByVal bErrorView As Boolean) As Long
但它没有按预期工作,我猜 VB6 布尔值在某处丢失或转换不正确。
我目前正在使用 VB6 Boolean、C++ BOOL 和 C++ bool。 我知道这不太好,但我没有看到任何其他方式。
有人发现我的代码有问题吗?
【问题讨论】:
-
看起来STDCALL函数和VB6使用的是两个不同的函数。也使
SetParameterstdcall。 -
@BenVoigt 我的 C++ DLL 通过其属性设置为调用约定 __stdcall (/Gz)。我应该写“extern“C”int SetParameter”吗?你能给我准确的拼写吗?我应该保留“extern C”吗?
-
extern "C" __declspec(dllexport) int __stdcall SetParameter(BOOL bErrorView)应该没问题。在使用/Gz时,不需要指定__stdcall,但它不会造成任何伤害,所以我会明确说明。 -
@BenVoigt 啊,是的……我快到了。传递一个 VB6 Boolean True 变量已经给出了正确的结果(虽然在我按照你的建议更改声明之前它实际上并没有做任何事情),但是传递一个 False 不会做任何事情。这就是为什么我想知道 (bErrorView != FALSE);真的是对的。
-
尝试将 VB6 参数更改为
ByVal Long。如果 VB6 只存储一个字节,而 C++ 读取四个字节,那么即使第一个字节为零,其他字节中的垃圾也会使整体值为!= FALSE。