Calling COM interface without type library
Posted on 2003-03-27
I have a COM interface (the Still Image Aquisition library in sti.dll) that I need to call from VB.
My test code so far is;
Private Const STI_VERSION = &H2
Private Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" _
(ByVal lpModuleName As String) As Long
Private Declare Function StiCreateInstance Lib "sti.dll" Alias "StiCreateInstanceA" _
(ByVal hInst As Long, _
ByVal dwVer As Long, _
ByVal ppSti As Long, _
ByVal punkOuter As Long _
) As Long
Private Declare Sub CopyMemory Lib "kernel32" _
Alias "RtlMoveMemory" _
(lpvDest As Any, _
lpvSource As Any, _
ByVal cbCopy As Long)
Private Sub Command2_Click()
Dim lRet As Long
Dim lProcessHandle As Long
Dim dwVer As Long
Dim oTemp As Object
Dim ppSti As Object
Dim lPointerToInterface As Long
Dim pwszDeviceName As String ' LPWSTR
Dim pdwEventCode As Long ' DWORD
Dim pwszEventName As String ' LPWSTR
' The following is required for design time.
lProcessHandle = GetModuleHandle("vb6.exe" & Chr(0))
If (lProcessHandle = 0) Then
' Must be in run time.
lProcessHandle = GetModuleHandle(App.EXEName & ".exe" & Chr(0))
dwVer = STI_VERSION
lRet = StiCreateInstance(lProcessHandle, dwVer, VarPtr(lPointerToInterface), 0&)
If (lRet = 0) Then
' Turn the pointer into an illegal, uncounted interface
CopyMemory oTemp, (lPointerToInterface), 4
' Call AddRef method, so that ppSti becomes a legal reference.
Set ppSti = oTemp
' Destroy the illegal reference by setting it to Nothing without calling Release.
CopyMemory oTemp, 0&, 4
' We now have an STI object available to call methods on.
pwszDeviceName = String(1024, Chr(0))
pwszEventName = String(1024, Chr(0))
pdwEventCode = 0
lRet = ppSti.GetSTILaunchInformation(pwszDeviceName, pdwEventCode, pwszEventName)
The first CopyMemory call fails, I am not passing a correct pointer somehow. The StiCreateInstance call required a pointer to a pointer where it would store the COM interface pointer. This call succeeds and I am trying to make use of that pointer by converting it into a generic object.
I am nearly there with this, but get a problem when copying pointers. I think that there may be more problems ahead because the functions are not strongly prototyped.
Is this the way to go or are there better ways of accessing this interface? For example, should I attempt to translate the C++ interface to a VB type library (never done this before) and use that? As far as I can see, no one else has a type library for this.
Hope someone can help.