C#调用C++DLL–委托

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.InteropServices;

namespace Test
{
    class DLLLoader
    {
            [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);

            IntPtr DllLib;//DLL文件名柄     
            #region 构造函数
            public DLLLoader()
            { }
            public DLLLoader(string dllpath)
            {
                DllLib = LoadLibrary(dllpath);
            }
            #endregion
            ///      
            /// 析构函数     
            ///      
            ~DLLLoader()
            {
                FreeLibrary(DllLib);//释放名柄     
            }
            public void initPath(string dllpath)
            {
                if (DllLib == IntPtr.Zero)
                {
                    DllLib = LoadLibrary(dllpath);
                }
            }
            ///      
            /// 获取DLL中一个方法的委托     
            ///      
            ///      
            ///      
            ///      
            public Delegate InvokeMethod(string methodname, Type methodtype)
            {
                IntPtr MethodPtr = GetProcAddress(DllLib, methodname);

                return (Delegate)Marshal.GetDelegateForFunctionPointer(MethodPtr, methodtype);
            }      

    }
}

************调用***************
        DLLLoader loaddll = new DLLLoader("E:\\workspaces\\WpfApplication1\\Debug\\DLL.dll");//实例化加载DLL文件的类,,如上     
        public delegate int delegateadd(ref int a);//声明此方法的一个委托

public void testMethod()
{
        int a = 1;
        delegateadd m = (delegateadd)loaddll.InvokeMethod("add", typeof(delegateadd));//获取其中方法的委托     
        int re = m(ref a);//得到RE,成功  
}

**************DLL**************
extern "C" __declspec(dllexport) int add(int & a);

int add(int & a)
{
	a = 10;
	return 20;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值