VB6 CDECL


Author: Dave
Date: 09.13.16 - 5:19am



So normally when calling cdecl exports from VB i do a generated asm thunk technique with CallWindowProc to launch it.( Example at bottom or download here)

Looking through the vbforums today I found a couple more. Archiving them here so I can find them again!

A TLB based one from The Trick (local copy) - Note compiled exe only

and one from Ben321 below.

Private Declare Function DispCallFunc Lib "oleaut32.dll" ( _
     ByVal pvInstance As Long, _
     ByVal oVft As Long, _
     ByVal cc As Long, _
     ByVal vtReturn As Integer, _
     ByVal cActuals As Long, _
     ByRef prgvt As Integer, _
     ByRef prgpvarg As Long, _
     ByRef pvargResult As Variant _
) As Long


Private Function CallCDECL(ByVal FuncAddr As Long, ByRef Params() As Variant, ByVal ReturnType As VbVarType) As Variant Dim ParamCount As Long Dim ParamTypes() As Integer Dim ParamPtrs() As Long Dim n As Long ParamCount = UBound(Params) + 1 If ParamCount > 0 Then ReDim ParamTypes(ParamCount - 1) ReDim ParamPtrs(ParamCount - 1) For n = 0 To ParamCount - 1 ParamTypes(n) = VarType(Params(n)) ParamPtrs(n) = VarPtr(Params(n)) Next n DispCallFunc 0, FuncAddr, 1, ReturnType, ParamCount, ParamTypes(0), ParamPtrs(0), CallCDECL Else DispCallFunc 0, FuncAddr, 1, ReturnType, ParamCount, ByVal 0, ByVal 0&, CallCDECL End If End Function




My example:
Private Declare Function CallAsmAddr Lib "user32" Alias "CallWindowProcA" (
    ByVal lpCode As Long, ByVal hwnd As Long,
    ByVal msg As Long, ByVal wParam As Long,
    ByVal lParam As Long
) As Long

Private Declare Function VirtualAlloc Lib "kernel32" (
    ByVal lpAddress As Long, ByVal dwSize As Long, 
    ByVal flAllocationType As Long, ByVal flProtect As Long
) As Long

Private Declare Function VirtualFree Lib "kernel32" (
    ByVal lpAddress As Long, ByVal dwSize As Long, 
    ByVal dwFreeType As Long
) As Long

Private Declare Sub RtlMoveMemory Lib "kernel32" (
    ByVal Destination As Long,
    ByVal Source As Long, ByVal Length As Long
)


'should be dep safe..
Function CallCdecl(lpfn As Long, ParamArray args()) As Long

    Dim asm() As String
    Dim stub() As Byte
    Dim i As Long
    Dim argSize As Byte
    Dim ret As Long
    Const PAGE_RWX      As Long = &H40
    Const MEM_COMMIT    As Long = &H1000
    Dim asmAddr As Long
    Dim sz As Long
    
    Const depSafe = True
    
    If lpfn = 0 Then Exit Function
    
    'push asm(), "CC"  'enable this to debug asm
    
    'we step through args backwards to preserve intutive ordering
    For i = UBound(args) To 0 Step -1
        If Not IsNumeric(args(i)) Then
            MsgBox "CallCdecl Invalid Parameter #" & i & " TypeName=" & TypeName(args(i))
            Exit Function
        End If
        push asm(), "68 " & lng2Hex(CLng(args(i)))  '68 90807000    PUSH 708090
        argSize = argSize + 4
    Next

    push asm(), "B8 " & lng2Hex(lpfn)        'B8 90807000    MOV EAX,708090
    push asm(), "FF D0"                      'FFD0           CALL EAX
    push asm(), "83 C4 " & Hex(argSize)      '83 C4 XX       add esp, XX     'cleanup args
    push asm(), "C2 10 00"                   'C2 10 00       retn 10h        'cleanup our callwindowproc args
    
    stub() = toBytes(Join(asm, " "))
    
    If Not depSafe Then
        CallCdecl = CallAsm(stub(0), 0, 0, 0, 0)
        Exit Function
    End If
    
    sz = UBound(stub) + 1
    asmAddr = VirtualAlloc(ByVal 0&, sz, MEM_COMMIT, PAGE_RWX)
    
    If asmAddr = 0 Then
        MsgBox "Failed to allocate RWE memory size: " & sz, vbInformation
        Exit Function
    End If
    
    RtlMoveMemory asmAddr, VarPtr(stub(0)), sz
    CallCdecl = CallAsmAddr(asmAddr, 0, 0, 0, 0)
    VirtualFree asmAddr, sz, 0
    
    
End Function





Comments: (0)

 
Leave Comment:
Name:
Email: (not shown)
Message: (Required)
Math Question: 93 + 4 = ? followed by the letter: N 



About Me
More Blogs
Main Site
Posts:
FireFox temp dir
OCX License
Extract substring
VB6 Console Apps
VB6 UDTs
VB6 Debugger View As Hex tooltips
VB6 - C Share registry data
VB6 Addin Missing Menus
VB6 Class Init Params
VB6 isIn function
Python and VB6
Python pros and cons
download web Dir
vc rand in python
VB6 Language Enhancement
Register .NET as COM
VB6 CDECL
UDT Tricks pt2
Remote Data Extraction
Collection Extender
VB6 FindResource
CDO.Message
DirList Single Click
Reset CheckPoint VPN Policy
VB6 BSTR Oddities Explained
SafeArrays in C
BSTR and Variant in C++
Property let optional args
Misc Libs
Enum Named Pipes
Vb6 Collection in C++
VB6 Overloaded Methods
EXPORT FUNCDNAME Warning
VB6 Syncronous Socket
Simple IPC
VB6 Auto Resize Form Elements
Mach3 Automation
Exit For in While
C# self register ocx
VB6 Class Method Pointers
JS Debugger
Duktape Debug Protocol
QtScript 4 VB
Vb6 Named Args
vb6 Addin Part 2
VB6 Addin vrs Toolbars
OpenFile Dialog MultiSelect
Duktape Example
DukTape JS
VB6 Unsigned
.Net version
TitleBar Height
.NET again
VB6 Self Register OCXs
Query Last 12 Mos
Progid from Interface ID
VB6 to C Array Examples
Human Readable Variant Type
ScriptBasic COM Integration
CodeView Addin
ScriptBasic - Part 2
Script Env
MSCOMCTL Win7 Error
printf override
History Combo
Disable IE
API Hooking in VB6
Addin Hook Events
FastBuild Addin
VB6 MemoryWindow
Link C Obj Files into VB6
Vb6 Standard Dlls
CStr for Pascal
Lazarus Review
asprintf for VS
VB6 GlobalMultiUse
Scintilla in VB6
Dynamic Highlight
WinVerifyTrust, CryptMsgGetParam VB6
MS GLEE Graphing
printf for VB6
C# App Config
Tero DES C# Test
VC 2008 Bit Fields
Speed trap
C# Db Class Generator
VB6 vrs .NET (again)
FireFox Whois Extension
git and vb6
Code Additions
Compiled date to string
C# ListView Sorter
VB6 Wish List
C# Process Injection
CAPTCHA Bots
C# PE Offset Calculator
VB6 Async Download
Show Desktop
coding philosophy
Code release
Dll Not Found in IDE
Advanced MSScript Control
random tip
Clipart / Vector Art
VB6 Callback from C#
Binary data from VB6 to C#
CSharp and MsScriptControl
HexDumper functions
Js Beautify From VB6 or C#
vb6 FormPos
Inline Asm w VB6
The .NET Fiasco
One rub on computers
Universal extractor