extern "C")避免 C++ Name Mangling__stdcall 呼叫慣例(VB/VBA 預設).def 匯出定義,鎖定匯出名稱純淨無修飾BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID) {
switch (reason) {
case DLL_PROCESS_ATTACH: /* 初始化 */ break;
case DLL_PROCESS_DETACH: /* 清理 */ break;
}
return TRUE;
}
編譯選項:/entry:"DllMain"
// MyDLL.h
extern "C" WORD WINAPI vbShiftRight(WORD nValue, WORD nBits);
// MyDLL.cpp
WORD WINAPI vbShiftRight(WORD nValue, WORD nBits) {
return nValue >> nBits;
}
LIBRARY "MyDLL"
EXPORTS
vbShiftRight
無 .def 時,VC++ 會匯出 _vbShiftRight@8 等修飾名稱,VB 無法正確連結。
Declare Function vbShiftRight Lib "MyDLL.dll" _
(ByVal nValue As Integer, ByVal nBits As Integer) As Integer
Sub Test()
Debug.Assert vbShiftRight(4, 2) = 1
End Sub
// MyDLL.odl
library MyLib {
[helpstring("Shifts bits right"), version(1.0)]
module MyModule {
[entry("vbShiftRight")]
short _stdcall vbShiftRight([in] short nValue, [in] short nBits);
};
}
編譯 midl MyDLL.odl 產生 .tlb,VB 專案參考該型別庫即可享有 IntelliSense 與型別檢查。