Monday, 18 April 2011

Creating a dll in C and how to use it in C++ program

The following Steps are required
1.Create a new project in Visual Studio 2010
2.Under Visual C tab create an empty project

-----------------------------------------------------------------

#include<iostream>
//C++ style header decoration in the dll
  __declspec(dllexport)  int __stdcall add(int a ,int b )
{
return a+b;
}
//c style header declartion in the dll
 extern "C"  __declspec(dllexport) int  _stdcall sub(int a ,int b )
{
return a-b;
}
//C++ style header decoration in the dll
  __declspec(dllexport)int _cdecl mul(int a ,int b )
{
return a*b;
}
//c style header declartion in the dll
extern "C" __declspec(dllexport)int  _cdecl divide(int a ,int b )
{
return a/b;
}
----------------------------------------------------------------------
Before Building the solution change the  solution configration from debug mode to release mode
go to Project property 
in configuration manager change the  configuration to release
In project properties change the configuration type to Dynamic link library(.dll)
--------------------------------------------------------------------------------------------

Build this project. 
there are two types of calling conventions used   (__stdcall)  and   (__cdecl)
By default  the C++ style header decoration is used.
But if we want to use the c style decoration. we will use  extern "C" .

--------------------------------------------------------------------------------------------
To use a C Dll in C++ C project.
Create a C project in Visual studio .
we will use the all function in the dll.
--------------------------------------------------------------------------------------------
#include<iostream>
using namespace std;

//C++ style header decoration in the dll
int __stdcall add(int a ,int b );

//C style header declartion in the dll
extern "C" int  _stdcall sub(int a ,int b );

//C++ style header decoration in the dll
int _cdecl mul(int a ,int b );

//C style header declartion in the dll
extern "C" int  _cdecl divide(int a ,int b );

void main()
{
cout<<add(3,4);
cout<<sub(4,3);
cout<<mul(3,4);
cout<<divide(4,2);
}

-------------------------------------------------------------

In the project property  Go to  VC++ Directories   .In librery Dependencies add the  full path where the dll is placed....


In the linker -->Input-->additional Dependencies -->add the .lib file of the dll generated.


-------------------------------------------------------------------------------------
Compile the .cpp file.

No comments:

Post a Comment