VB 應用常需呼叫 VC++ 編寫的 DLL 或 ActiveX 控件,兩語言在參數型別、記憶體佈局、呼叫慣例上差異大,易產生難以除錯的錯誤。本文系統整理四大類經典問題與解法。
VB 與 VC 結構定義一致,注意 32 位環境下 Long (4 bytes) 對應 VC long/int,即可正確傳遞。
VB 結構緊湊排列,VC 為了對齊會在 Double 前插入填充位元組,導致記憶體佈局不一致,參數傳遞錯誤。
' VB 結構 (12 bytes)
Type Person
Age As Long ' 4 bytes
Height As Double ' 8 bytes
End Type
// VC 結構 (16+ bytes,Age 後插入 4 bytes padding)
struct Person {
long Age;
double Height; // 偏移 8,非 4
};
在 VB 結構中手動插入填充成員,使每個 Double 前的總位元組數為 8 的倍數:
Type Person
Age As Long
TempSt As String * 4 ' 4 bytes padding
Height As Double
End Type
VC 端同步修改結構定義,即可正確對齊。
關鍵:補位成員的大小與位置必須精確,放在 Double 之前才有效。
VC DLL 匯出函數傳回指標(Long),VB 接收後使用,用畢必回呼 VC 釋放,避免記憶體洩漏。
' VC
char* __stdcall CreateStringBuffer(long Length) {
return (char*)malloc(Length);
}
void __stdcall FreeStringBuffer(char* p) { free(p); }
' VB
Declare Function CreateStringBuffer Lib "MyDll.dll" (ByVal Length As Long) As Long
Declare Sub FreeStringBuffer Lib "MyDll.dll" (ByVal p As Long)
Dim ptr As Long
ptr = CreateStringBuffer(100)
' 使用 CopyMemory 等 API 讀寫記憶體
FreeStringBuffer ptr
利用指標(Long)跨越進程邊界(In-process Server 共享位址空間):
[in/out] long*。get/put_Property 以 memcpy 複製結構內容。VarPtr 或 API) 傳給屬性。' VB
Dim StudentProp As Person
Dim StudentAddr As Long
StudentProp.Age = 23
StudentProp.Height = 1.78
StudentAddr = VarPtr(StudentProp) ' 需正確取得位址
AXCtrl.Student = StudentAddr
VB Len 回傳字元數,LenB 回傳位元組數(DBCS),混雜字串兩者皆不準。解法:VC 撰寫 DLL 函數呼叫 lstrlen (ANSI 版) 取得實際顯示寬度(英文 1、中文 2)。
' VC
long __stdcall SizeOfVbString(char* str) { return lstrlen(str); }
' VB
Declare Function SizeOfVbString Lib "StrLen.dll" (ByVal str As String) As Long
Dim len As Long
len = SizeOfVbString("A中國人") ' 回傳 7