Sunday, September 28, 2008

Creating a C++ DLL in Visual Studio 2005

It's real freaking easy...

1-File,New,Project,Select Visual C++, and Select Win32 Project. Give it a name. Click OK.



2-It will take you to a new screen. Click on Application Settings, and select the DLL
radio button. Click on Finish.





Paste the following code....

int _stdcall addTwoNumbers(int x, int y)
{
// _stdcall is the calling convention is used to call Win32 API functions.
return (x+y);
}




3-Now let's make sure we export this function, so other applications can use it. We export it as a symbol(don't worry about this fancy word symbol for now). As you can see this function simply just receives 2 values and then returns their sum. We export it by creating a .def file. Right-click on your project and select add, new item. Give it a name and click OK.







4-Paste the following code below the LIBRARY line...

EXPORTS
addTwoNumbers @1

5-Rebuild the solution.



6-Create a simple vb.net console application, just compile it's skeleton for now.Copy the dll you created to the bin\Debug of the vb.net project you just created.Paste the following code. Make sure to replace.. dll2forScreenShots.dll with the name of your dll.


Private Declare Function addTwoNumbers _
Lib "dll2forScreenShots.dll" _
(ByVal x As Integer, ByVal y As Integer) _
As Integer
Sub Main()
Console.WriteLine(addTwoNumbers(9, 7))

'should display 16
Console.ReadLine()
End Sub


7-Compile and run, and you should have the number 16 displaying.

No comments: