Wednesday, June 10, 2009

Passing Visual Basic Arrays to Assembly DLL Modules

Programmers can learn much about the innards of visual basic by doing some assembly language programming. Assembly language reveals the underlying computer architecture, and it harbors all of the secrets many programmers seek. Outside of educational value, Programmers can also write assembly modules that can be called from visual basic applications.

While a complete introduction to assembly language is beyond the scope of this article, programmers who know some of the x86 assembly language should have no trouble creating assembly DLL files for use in visual basic. The process of creating an assembly DLL file is the same as creating a DLL file in C++, and the calling convention is still standard call; however, programmers need to know some information about variable sizes and structure before they can create assembly DLL files for visual basic.

The following information is how variables correspond between visual basic and assembly language. This list is not complete, but other variables can be looked up on MSDN.

Visual basic – Assembly
byte – BYTE
Char – BYTE
boolean – WORD
Integer – WORD
Long – DWORD
Short – DWORD
String – DWORD Variable is passed by pointer.

While variables correspond quite harmoniously between visual basic and assembly, arrays are a different story. Visual basic does not store arrays in a straight forward manner; instead, visual basic stores arrays in an OLE_SAFEARRAY structure. When programmers wish to pass arrays to assembly language DLL files, they must work with the structure of the array.


SAFEARRAYBOUND struct
cElements DWORD ? ;Number of Elements
lLbound DWORD ? ; Lower Boundary
SAFEARRAYBOUND ends

OLE_SAFEARRAY struct
cDims WORD ? ; Number of dimensions
fFeatures WORD ? ; Bitfield indicating attributes
cbElements DWORD ? ; size of an element of the array
cLocks DWORD ? ; lock counter 0=Locked
pvData DWORD ? ; Pointer to data
rgsabound SAFEARRAYBOUND <> ; Contains info for dimensions
OLE_SAFEARRAY ends

Finally, here the following is an example of how to reference the structure from MASM32.

testfunction proc myArray:DWORD
mov eax, myArray
mov edx, [eax] ;EDX now has our safearray.

'Assign 1st value to eax.
mov eax, (OLE_SAFEARRAY ptr [edx]).pvData
ret
testfunction endp

No comments:

Post a Comment