【问题标题】:Calling C DLL from Visual Basic 6: Double data type not working从 Visual Basic 6 调用 C DLL:双数据类型不起作用
【发布时间】:2010-08-23 05:41:32
【问题描述】:

我将一个简单的用户定义类型 (UDT) 从 Visual Basic 6 传递到一个 C DLL。它工作正常,除了 double 数据类型显示为 0。

C DLL:

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <stdio.h>

typedef struct _UserDefinedType
{
    signed int      Integer;
    unsigned char   Byte;
    float           Float;
    double          Double;
} UserDefinedType;

int __stdcall Initialize ( void );
int __stdcall SetUDT ( UserDefinedType * UDT );

BOOL WINAPI DllMain ( HINSTANCE Instance, DWORD Reason, LPVOID Reserved )
{
    return TRUE;
}

int __stdcall Initialize ( void )
{
    return 1;
}

int __stdcall SetUDT ( UserDefinedType * UDT )
{
    UDT->Byte = 255;
    UDT->Double = 25;
    UDT->Float = 12345.12;
    UDT->Integer = 1;

    return 1;
}

Visual Basic 6 代码:

Option Explicit

Private Type UserDefinedType
    lonInteger As Long
    bytByte As Byte
    sinFloat As Single
    dblDouble As Double
End Type

Private Declare Function Initialize Lib "C:\VBCDLL.dll" () As Long
Private Declare Function SetUDT Lib "C:\VBCDLL.dll" (ByRef UDT As UserDefinedType) As Long

Private Sub Form_Load()

    Dim lonReturn As Long, UDT As UserDefinedType

    lonReturn = SetUDT(UDT)

    Debug.Print "VBCDLL.SetUDT() = " & CStr(lonReturn)

    With UDT
        Debug.Print , "Integer:", CStr(.lonInteger)
        Debug.Print , "Byte:", CStr(.bytByte)
        Debug.Print , "Float:", CStr(.sinFloat)
        Debug.Print , "Double:", CStr(.dblDouble)
    End With

End Sub

Visual Basic 的输出:

VBCDLL.SetUDT() = 1
              Integer:      1
              Byte:         255
              Float:        12345.12
              Double:       0

如您所见,双精度数显示为 0,而它应该是 25

【问题讨论】:

  • 您可以尝试在第一个FloatDouble 之间插入另一个Float,看看会发生什么。也许 C 和 Visual Basic 不同意如何填充 double

标签: c dll vb6 double user-defined-types


【解决方案1】:

VB6 的 UDT 在地址为 4 的倍数处对齐双精度数。以下是在 C 中如何应对:

#pragma pack(push,4)
typedef struct _UserDefinedType 
{ 
    signed int      Integer; 
    unsigned char   Byte; 
    float           Float; 
    double          Double; 
} UserDefinedType;
#pragma pack(pop)

【讨论】:

  • +1 我还建议查看Microsoft advice 编写要从 VB 调用的 C DLL。最初与 VB5 一起发布,但仍与 VB6 相关。例如,它提到 VB6 需要 4 字节打包。
  • 这里没有说我有任何答案。无论如何,非常感谢你们(Windows 程序员)的代码和 MarkJ 的链接。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多