打印本文 打印本文 关闭窗口 关闭窗口
利用动态创建自动化接口实现VB的函数指针调用
作者:武汉SEO闵涛  文章来源:敏韬网  点击数1709  更新时间:2009/4/23 16:37:59  文章录入:mintao  责任编辑:mintao
StdDispatch(Nothing, m_Delegator, ti, Result)
        If i = 0 Then
            Set m_FunctionPtr = Result
            Set Create = m_FunctionPtr
        End If
    End If
End Function

Private Sub Class_Initialize()
    ''''thunk的机器码,加nop是为了清晰
    m_Thunk(0) = &H4244C8B      ''''mov ecx, [esp+4]           获得this pointer
    m_Thunk(1) = &H9004418B     ''''mov eax, [ecx+4]   nop     获得m_pFunc
    m_Thunk(2) = &H90240C8B     ''''mov ecx, [esp]     nop     得到返回地址
    m_Thunk(3) = &H4244C89      ''''mov [esp+4], ecx           保存返回地址
    m_Thunk(4) = &H9004C483     ''''add esp, 4         nop     重新调整堆栈
    m_Thunk(5) = &H9090E0FF     ''''jmp eax                    跳转到m_pFunc
End Sub

''''Helper.cls     ''''其实不是Helper,只是原来的名字而已,包含供测试的函数
Attribute VB_Name = "Helper"
Option Explicit

Sub Test1(ByRef this As Long)
    MsgBox "Test1", vbOKOnly, "hehe"
End Sub

Sub Test(ByVal s As String)
    MsgBox s, vbOKOnly, "hehe"
End Sub
  
 
''''测试程序 
Option Explicit

Private Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As Long
Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, ByVal lpProcName As String) As Long

Private Sub Form_Load()
    Dim p As FunctionPtr
    Set p = New FunctionPtr
   
    Dim d As Object
    Set d = p.Create(AddressOf Test, vbEmpty, vbString)
   
    d.Invoke ("hehe")
   
    Dim hModUser32
    Dim pMessageBoxW As Long
   
    hModUser32 = GetModuleHandle("User32")
    pMessageBoxW = GetProcAddress(hModUser32, "MessageBoxW")
    Dim mbw As New FunctionPtr
    Dim MessageBoxW As Object
    Set MessageBoxW = mbw.Create(pMessageBoxW, vbLong, vbLong, vbString, vbString, vbLong)
    ''''MessageBoxA 0, "hehe,form MessageBoxA", "", 0
    MessageBoxW.Invoke 0, "hehe,form MessageBoxW", "", 0
End Sub
  
 
''''Project文件
Type=Exe
Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\SYSTEM\
STDOLE2.TLB#OLE Automation
Form=Form1.frm
Module=Helper; Helper.bas
Class=FunctionPtr; FunctionPtr.cls
IconForm="Form1"
Startup="Form1"
HelpFile=""
Title="工程1"
ExeName32="工程1.exe"
Command32=""
Name="工程1"
HelpContextID="0"
CompatibleMode="0"
MajorVer=1
MinorVer=0
RevisionVer=0
AutoIncrementVer=0
ServerSupportFiles=0
CompilationType=0
OptimizationType=2
FavorPentiumPro(tm)=0
CodeViewDebugInfo=-1
NoAliasing=0
BoundsCheck=0
OverflowCheck=0
FlPointCheck=0

FDIVCheck=0
UnroundedFP=0
StartMode=0
Unattended=0
Retained=0
ThreadPerObject=0
MaxNumberOfThreads=1 

上一页  [1] [2] 

打印本文 打印本文 关闭窗口 关闭窗口