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);
}
}

No comments: