Calling an assembly language DLL from VisualBasic
Here's a quick and simple example of how to call a DLL that was made in assembly from VB. There other ways to do this, but I find this method quite simple.What You'll Need
segment code use32 global _blah ; Add Param1 to Param2 and return that result ; This code can be simplified, but is written out this way to ; help explain it better _blah: push ebp mov ebp, esp ; typical code to start functions push ebx ; save ebx so we can use it mov eax, [ebp+8] ; Param1 goes into eax mov ebx, [ebp+12] ; Param2 goes into ebx add eax, ebx ; eax has the return value (Param1+Param2) pop ebx ; restore ebx and ebp and return pop ebp ret
default: nasm -f win32 blah.asm -o blah.o dllwrap --def blah.def --dllname blah -o blah.dll blah.o
Private Declare Function blah Lib "blah.dll" _ (ByVal Param1 As Long, _ ByVal Param2 As Long) As Long Private Sub Command1_Click() Dim x, y, i As Long x = 5 y = 10 i = blah(x, y) Text1.Text = i End Sub
The blah.asm holds a function in assembly that can be defined in C as:
int blah(int param1, int param2). This function simply adds param1
and param2 and returns that value. Note that VB (just like C) pushes
parameters on the stack from right to left. So the stack should look
like this after ebp is pushed onto the stack:
Just a bit of warning: If in your VB declare, you forget to define the return value type (aka, the "As Long" at the end of the declare), VB will push an extra parameter on the stack before the return address and all your parameters will be off by 4 bytes. Nice feature (insert sarcasm here).
In the asm file, don't forget the "segment code use32" or the "global _blah" lines. All function names need to have an underscore infront of them in your asm file, but no underscore in the VB code. The blah.def file defines which functions should be exported. In the make file, blah.asm is assembled with the -f win32 option (for obvious reasons) and then the object file is turned into a DLL using dllwrap. I believe dllwrap is a part of the mingw set, either in the gcc part or the msys part.
In the VB code, just define the function as if it were a normal C function from a DLL, and it should all work. That's it :).
Copyright 1997-2021 - Michael Kohn