Thursday, March 22, 2012

Win32 DLL Creation And Using in C#

Create Win32 Project choose Dll Empty Project name as sum
create header file sum.h
==============================================================
#ifndef _SUM_H_
#define _SUM_H_
#include <windows.h>
extern "C" int add(int a,int b);
#endif //_SUM_H_

==============================================================
create source file sum.cpp
==============================================================
#include"sum.h"
int add(int a,int b)
{
    return (a+b);
}
==============================================================
create Module defintion file sum.def
==============================================================
LIBRARY sum
EXPORTS add
==============================================================

 build the project. before the set the compiler option as






 Confirm with highlighted settings before build operation.

Build the Project.

you will get the executable Dynamic link library (sum.dll).

Guide to check the builded DLL
========================================================================
open visual studio command prompt to check the exported libray without any name mangling or not

type at prompt
>dumpbin /exports sum.dll

Microsoft (R) COFF/PE Dumper Version 10.00.40219.01
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file sum.dll

File Type: DLL

  Section contains the following exports for sum.dll

    00000000 characteristics
    4F6B36CD time date stamp Thu Mar 22 19:57:25 2012
        0.00 version
           1 ordinal base
           1 number of functions
           1 number of names

    ordinal hint RVA      name

          1    0 00001000 add

  Summary

        2000 .data
        2000 .rdata
        1000 .reloc
        1000 .rsrc
        5000 .text
=====================================================================

Usage the Dynamic link library in C#.

I create a winform application.
and copy the Dll file to folder which executable going to build.
at form_load event.
Copy the usage file.
sample source.
====================================================================
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace test
{
    public partial class Form1 : Form
    {
        [DllImport("sum.dll")]
        private static extern int add(int a, int b);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Trace.WriteLine(add(10, 15));
        }
    }
}
======================================================================

Run the file you will find the output  at the trace.
as
25

find the source for  reference @
https://docs.google.com/open?id=0B8j-6CFq6hsGY3lqQnl2dmZTRUtfUTNCTkNhTWFaZw