Saturday, September 1, 2012

DLL:Dynamic linked library export and import. A simple displaying a string program.


Prerequisite: One should know what a DLL is. In short dynamic-link library  is a module that contains functions and data that can be used by another module.

The example which I have taken is to create a DLL to display a string.

How to create a Dynamic linked library in C language and export it ?
1.       Open visual studio 2010
2.       Click on new project
3.       Select Visual C++
4.       Select Win32
5.       Select Win32 Project and enter the project name in the Name row. In my case    “MyDllLibrary”.
6.       Click on application settings in the wizard
7.       Select application type as Dll and Select empty project.
8.       Click on finish
9.       Right click on source file and click on Add a new item
10.    Select C++ File(.cpp) and give a name to the file. In my case “DisplayProgram”.
11.    DisplayProgram.cpp file will be created under Source Files folder.
12.    Right click on DisplayProgram.cpp file and rename it to “DisplayProgram.c”
13.    Now copy and paste the below code

Program to create a dll to display sting "Inside library".

    #include<stdio.h>
    __declspec(dllexportvoid display()
    {
       printf("Inside DLL");
    }    
14. Ctrl Save
15. Press F7 or Build it using build option.
16. When Build is successful, Go to Project folder -> Debug. In my case “MyDllLibrary/Debug”
17. Inside debug folder MyDllLibrary file will be generated which is of type Dll if build is successful.


How to import C DLL library in C# code ?

1.       Open visual studio 2010
2.       Click on new project
3.       Select Other languages -> Visual C#
4.  Select Console application
5.       Enter the project name in the Name row. In my case “MyDllLibraryCall”.
6.  Select Program.cs (Default file which got created)
7.       Now copy and paste the below code


 Program to call the DLL in C#  language

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    namespace MyDllLibraryCall
    {
        class Program
        {
            [DllImport(" MyDllLibrary .dll",EntryPoint="display")]
            public static extern void display();
            static void Main(string[] args)
            {
                display();
                Console.ReadLine();
            } 
        }
    }


8.  Ctrl Save
9.  Copy the MyDllLibrary.dll file from MyDllLibrary/Debug folder and paste it in MyDllLibraryCall/Bin/Debug/ folder.
10. Now run the C# code using F5 or Run Option ( Green arrow)


Output “Inside DLL” will appear on console.

No comments:

Post a Comment