Wednesday, May 28, 2008

Writing VB.Net app with c or C++ Dll

Added for my reconnaissance.

Step 1. Create a VC project (I used VC++ 6). An empty win32 DLL. The main things are below

Step 1a: For all the functions that needs to be exported, add "_stdcall" before their declaration and definition. For ex, I added
long _stdcall MyExportedFunction(int myinteger)

One VERY IMPORTANT thing to note. The return has to be something other than void as this causes an incompatibility between the DLL and the VB and the application will end up crashing.

Step 1b: Make sure to have a .def added to the VC project. The contents of my def file are


 MyVCLibrary.def : Declares the module parameters for the DLL.
LIBRARY "MyVCLibrary"
DESCRIPTION 'My VC Library DLL'

EXPORTS
; Explicit exports can go here
MyExportedFunction
My exported function prototype is
long _stdcall MyExportedFunction(int);

Now, thats it for the DLL. Compile and get it ready.

Step 2a: Create the VB.NET (I used Visual Studio 2008). In the Form Class, create a declaration as below (in a single line)


Declare Function MyExportedFunction Lib 
"MyVCLibrary.dll" (ByVal pcFilePath As Integer
) As Long

Step 2b: Call the function as below
Call MyExportedFunction(10)
. That's about pretty much to it.