Search This Blog

Saturday, November 22, 2008

An Example to call MFC DLL using function pointer in C#.net

//An Example to call MFC DLL using function pointer in C#.net
  1. Create new C#.Net windows application.
  2. Copy the "MyDll.dll" to your project path, which we created in this post Click here.
  3. Create two Textbox textBox1 and textBox2.

using System.Runtime.InteropServices; //Add this Line

namespace WindowsApplication1
{
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
//Add the Following Lines
IntPtr MyDll = LoadLibrary("MyDll.dll");
IntPtr procaddr = GetProcAddress(MyDll, "egAdd");
MyAdd mAdd = (MyAdd)Marshal.GetDelegateForFunctionPointer(procaddr, typeof(MyAdd));
int a = Convert.ToInt32(textBox1.Text);
int b = Convert.ToInt32(textBox2.Text);
int nRes = mAdd(a, b);
MessageBox.Show(nRes.ToString());
}
internal delegate int MyAdd(int a,int b);
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(String dllname);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, String procname);
}
}

C#.Net code to call MFC DLL

This is the code to call a function from vc++ DLL
(for example "MyDll.dll" which we created in this post click here )
  1. Create a new C#.net windows application.
  2. Copy the "MyDll.dll" to your project path, which we created in this post Click here.
  3. Add this this following lines as below.
//using System.Runtime.InteropServices is used to call dll function in C#
using System.Runtime.InteropServices; //add this line

namespace WindowsApplication1
{
public partial class Form1 : Form
{

[DllImport("MyDll.dll", CharSet=CharSet.Auto)] //add this line
internal static extern Int32 egAdd(int a, int b); //add this line

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int nRes = egAdd(2, 4); //add this line
MessageBox.Show(nRes.ToString()); //add this line
}

}
}