Search This Blog

Saturday, June 6, 2009

Creating a DLL in VC++, and using it in VB.net, C#.net

STEP 1. Start a new project in VC++ as "win32 DLL"

STEP 2. Declare function in header file i.e class1.h as

extern "C" __declspec(dllexport) int add_2_nos(int a, int b);
extern "C" __declspec(dllexport) int mul_2_nos(int a, int b);

Let rest things as it is.

STEP 3. Define functions in cpp file i.e in class1.cpp as

#include "class1.h"
extern "C" __declspec(dllexport) int add_2_nos(int a, int b)
{ int c;
c=a+b;
return c;
}


extern "C" __declspec(dllexport) int mul_2_nos(int a, int b)
{ int c;
c=a*b;
return c;
}


STEP 4. Save file & Build & Build DLL

This will create a DLL in the release folder.

-----------------------------------------------------------
DLL in vb.net

STEP 1. Create a new project as "windows application" and code as

Imports System
Imports System.Runtime.InteropServices
Public Class a
DllImport("c:\MyDLL\vc_dll.dll", CharSet:=CharSet.Auto) _ 'in angular brackets
Public Shared Function add_2_nos(ByVal a As Integer, ByVal b As Integer) As Integer
End Function
End Class



Public Class Form1
'on button click
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim b As Integer

b = a.add_2_nos(2, 3)
MessageBox.Show(b.ToString)
End Sub
End Class

STEP 2. Save it run it , click on button

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

DLL in C#

STEP 1. Create a new project as "windows application" and code as

using System;
using System.Runtime.InteropServices;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
[DllImport("C://MyDLL/vc_dll.dll")]
public static extern int add_2_nos(int a, int b);

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int a;
a= add_2_nos(3,40);
MessageBox.Show(a.ToString());

}
}
}

STEP 2. Save it run it click on button.........

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

Dll in copied in MyDLL folder in c: drive.

This dll can also be used in LabView

No comments:

Post a Comment