文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>c# api 动态加载c++的dll函数方法 ...

c# api 动态加载c++的dll函数方法 ...

时间:2010-08-11  来源:adsdassadfasdfasdf

C++函数如下:

// testdll3.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"

BOOL APIENTRY DllMain( HANDLE hModule,
                       DWORD ul_reason_for_call,
                       LPVOID lpReserved
      )
{
    return TRUE;
}


extern "C" __declspec(dllexport) int add(int * a,int * b)
{
return *a + *b;
}

C#中动态加载方法:

首先写一个加载DLL文件的类:

#region Win API 声明 class LoadDllAPI { [DllImport("kernel32.dll")] public extern static IntPtr LoadLibrary(string path); [DllImport("kernel32.dll")] public extern static IntPtr GetProcAddress(IntPtr lib, string funcName); [DllImport("kernel32.dll")] public extern static bool FreeLibrary(IntPtr lib); [DllImport("kernel32.dll")] public static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("user32", EntryPoint = "CallWindowProc")] public static extern int CallWindowProc(IntPtr lpPrevWndFunc, int hwnd, int MSG, int wParam, int lParam); } #endregion public class LoadDll { IntPtr DllLib;//DLL文件名柄 #region 构造函数 public LoadDll() { } public LoadDll(string dllpath) { DllLib = LoadDllAPI.LoadLibrary(dllpath); } #endregion /// <summary> /// 析构函数 /// </summary> ~LoadDll() { LoadDllAPI.FreeLibrary(DllLib);//释放名柄 } public void initPath(string dllpath) { if (DllLib == IntPtr.Zero) { DllLib = LoadDllAPI.LoadLibrary(dllpath); } } /// <summary> /// 获取DLL中一个方法的委托 /// </summary> /// <param name="methodname"></param> /// <param name="methodtype"></param> /// <returns></returns> public Delegate InvokeMethod(string methodname, Type methodtype) { IntPtr MethodPtr = LoadDllAPI.GetProcAddress(DllLib, methodname); return (Delegate)Marshal.GetDelegateForFunctionPointer(MethodPtr, methodtype); } }

以上方法编译.

调用:

* loadDLL.LoadDll loaddll = new loadDLL.LoadDll();//实例化加载DLL文件的类,,如上 * public delegate int delegateadd(IntPtr a,IntPtr b);//声明此方法的一个委托 //一个调用用的按钮 private void button1_Click(object sender, EventArgs e) { loaddll.initPath("testdll3.dll");//载入文件 delegateadd m = (delegateadd)loaddll.InvokeMethod("add", typeof(add));//获取其中方法的委托 int a=1;int b=2; int re = m(out a, out b);//得到RE=3,,成功 }

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载