2010-08-23 46 views
2

我將一個簡單的用戶定義類型(UDT)從Visual Basic 6傳遞給一個C DLL。能正常工作,除了數據類型,它表現爲0。從Visual Basic 6調用C DLL:雙重數據類型不工作

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

你可以嘗試插入另一'Float'第一'Float'和'Double'之間並看看會發生什麼。也許C和Visual Basic不同意如何去填充'double'。 – 2010-08-23 06:03:30

回答

3

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

+1我也建議看看[Microsoft的建議](http://vb.mvps.org/tips/vb5dll.asp)編寫C++ DLL從VB調用。最初與VB5一起發佈,但仍與VB6相關。例如,它提到VB6預計4字節打包。 – MarkJ 2010-08-23 08:15:37

+0

它沒有說我在這裏有任何答案。無論如何,感謝你們兩個人(Windows程序員)的代碼和MarkJ的鏈接。 :) – 2010-08-24 06:28:21