C# api 动态加载C++的DLL函数方法

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文件的类:

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
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);
}
}

 

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
* 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,,成功
}

 

 

以上方法编译.

调用:

 

转载于:https://www.cnblogs.com/xinle/articles/1798262.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值