我需要为DLL创建一个包装器,根据需要加载和卸载它(对于那些对此问题的背景感兴趣的人,请参阅 How to work around memory-leaking 3rd party DLL (no source code) accessed by Tomcat application?)。我在Visual Basic 6中执行此操作,并使用以下示例进行加载和卸载:
Private Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) As Long
Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
Private Sub cmdTestLoadingDLL_Click()
Dim lb As Long, pa As Long
lb = LoadLibrary("D:\projects\other\VB_DLLs\TestDLL\TestDLL.dll")
Msgbox "Library address: " + lb
FreeLibrary lb
End Sub
我可以看到使用Process Explorer在显示消息框时DLL被加载到内存中,然后被丢弃。但是,调用该方法自然是不够的 - 我需要访问动态加载的DLL中的方法。
我怎样才能做到这一点?我想在类mainClass中调用方法getVersion,它在TestDLL中,如下所示:
Private Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) As Long
Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
Private Sub cmdTestLoadingDLL_Click()
Dim lb As Long, pa As Long
Dim versionString As String
lb = LoadLibrary("D:\projects\other\VB_DLLs\TestDLL\TestDLL.dll")
versionString = "- From DLL: " + mainClass.getVersion
MsgBox versionString
FreeLibrary lb
End Sub
然而,行
versionString = "- From DLL: " + mainClass.getVersion
抛出错误“需要对象”。
答案 0 :(得分:3)
首先,由于您是通过LoadLibrary调用它,因此这里没有类 - 只导出函数供公众使用。所以你的mainClass引用永远不会工作。假设您有一个导出的函数 getVersion 。
我会尝试以下方法:
Private Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) As Long
Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, ByVal lpProcName As String) As Long
Private Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hWnd As Long, ByVal Msg As Any, ByVal wParam As Any, ByVal lParam As Any) As Long
Private Sub Foo
On Error Resume Next
Dim lb As Long, pa As Long
Dim versionString As String
Dim retValue as Long
lb = LoadLibrary("D:\projects\other\VB_DLLs\TestDLL\TestDLL.dll")
'retrieve the address of getVersion'
pa = GetProcAddress(lb, "getVersion")
'Call the getVersion function'
retValue = CallWindowProc (pa, Me.hWnd, "I want my version", ByVal 0&, ByVal 0&)
'release the library'
FreeLibrary lb
End Sub
答案 1 :(得分:2)
你需要在这个DLL上调用COM方法吗?如果是这样,我完全不确定这是可能的。
马修·柯兰德出色的Advanced Visual Basic 6是我看的第一个地方。那里有一些功能强大的引擎盖COM内容,可以绕过正常的VB6技术。
还有DirectCom,它允许您在不使用COM的情况下调用COM方法。从来没有自己使用它,但人们在VB6新闻组上聊聊它。