C# 中调用dll

    起因是因为相机有个手眼标定程序是用C#写的,中间留出来了机器人通信的地方,但是我们的机器人只提供了dll来控制。因此要结合起来的话,想试试通过C#来调用dll。

dll是什么

动态链接库(Dynamic Link Library)又称为“应用程序扩展”,在windows系统中,大多数应用程序并非仅有一个可执行文件exe,同时也包含一些相对独立(模块化)的dll文件。dll中存放函数代码实现,exe中存放dll中相应函数代码的地址,而且dll中的代码可以被多个exe调用而在内存中仅保留一份拷贝,从而节省了内存空间。

*******************************************************************************************

调用dll有两种链接方式:隐式链接显式链接,无论哪种方式都要求将dll和exe放在同一目录下。

1. 隐式链接

隐式链接需要三个文件:.h文件.lib文件 和 .dll文件

2. 显式链接

  • 显式链接只需要一个文件:.dll文件
  • 所谓显式链接,就是直接调用WIN32 API函数LoadLibraryGetProcAddressFreeLibrary显式地装载、卸载dll。

https://zhuanlan.zhihu.com/p/124221130

net平台上,调用dll文件有2种含义
1、调用托管dll,即你使用。net平台开发的dll,属于托管代码
2、调用非托管dll,即传统的dll,一般是C++,VB,DELPHI等等开发出来的,属于非托管代码。
从你的意思中看出来你现在是调用托管的dll,方法是 “在解决方案管理器” - “解决方案”(或项目) 中的任意地方, 右键“添加引用”,“浏览”,选择你需要调用的dll文件,确定即可,该dll会自动复制到bin目录,打包时也会自动复制到你发布的地方。
添加完了引用,现在如何调用呢?

如果有命名空间则引入命名空间,比如你的y。dll里面,是a命名空间,有一个b类,然后有一个无参数静态方法c
那么调用方法就是a.b.c(),跟你普通的使用类是一样的

然后是非托管dll
需要添加dll的名称,以及方法,也就是你所用到的dll的每个方法都需要添加一次,
[DllImport("msvcrt.dll")]    
public static extern int puts(string c);

https://blog.csdn.net/weixin_34358092/article/details/92500262 

*******************************************************************************************

一. C# 中静态调用C++动态链接

    1. 建立VC工程CppDemo,建立的时候选择Win32 Console(dll),选择Dll。

    2. 在CppDemo.cpp文件中添加这些代码。

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

3. 编译工程。

    4. 建立新的C#工程,选择Console应用程序,建立测试程序CSharpUsingDll_InteropDemo
    5. 在Program.cs中添加引用:using System.Runtime.InteropServices;

    6. 在pulic class Program添加如下代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace InteropDemo
{
    class Program
    {
        [DllImport("CppDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
        public static extern int Add(int a, int b); //DllImport请参照MSDN

        static void Main(string[] args)
        {
            Console.WriteLine(Add(1, 2));
            Console.Read();
        }
    }
}

  好了,现在您可以测试Add程序了,这是静态调用,需要将CppDemo编译生成的Dll放在CSharpUsingDll_InteropDemo程序的Bin/Debug目录下,否则出现下图中的错误

调用成功结果如下图所示

二. C# 中动态调用C++动态链接

 在第一节中,讲了静态调用C++动态链接,由于Dll路径的限制,使用的不是很方便,C#中我们经常通过配置动态的调用托管Dll,例如常用的一些设计模式:Abstract Factory, Provider, Strategy模式等等,那么是不是也可以这样动态调用C++动态链接呢?只要您还记得在C++中,通过LoadLibrary, GetProcess, FreeLibrary这几个函数是可以动态调用动态链接的(它们包含在kernel32.dll中),那么问题迎刃而解了,下面我们一步一步实验

    1.  将kernel32中的几个方法封装成本地调用类NativeMethod

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace InteropDemo
{
    public static class NativeMethod
    {
        [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
        public static extern int LoadLibrary(
            [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

        [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
        public static extern IntPtr GetProcAddress(int hModule,
            [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

        [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
        public static extern bool FreeLibrary(int hModule);
    }
}

2. 使用NativeMethod类动态读取C++Dll,获得函数指针,并且将指针封装成C#中的委托。原因很简单,C#中已经不能使用指针了,如下         
             int hModule = NativeMethod.LoadLibrary(@"D:\jaco\CSharpUsingDll_InteropDemo\CSharpUsingDll_InteropDemo\bin\Debug\CppDemo.dll");

            IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");

详细请参见代码

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

using System.Runtime.InteropServices;

namespace CSharpUsingDll_InteropDemo
{

    public static class NativeMethod
    {
        [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
        public static extern int LoadLibrary( [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

        [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
        public static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

        [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
        public static extern bool FreeLibrary(int hModule);
    }

    class Program
    {
       static void Main(string[] args)
        {
            //1. 动态加载C++ Dll
            int hModule = NativeMethod.LoadLibrary(@"D:\jaco\CSharpUsingDll_InteropDemo\CSharpUsingDll_InteropDemo\bin\Debug\CppDemo.dll");
            if (hModule == 0) return;

            //2. 读取函数指针
            IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");

            //3. 将函数指针封装成委托
            Add addFunction = (Add)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(Add));

            //4. 测试
            Console.WriteLine(addFunction(1, 2));
            Console.Read();
        }

        /// <summary>
        /// 函数指针
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        delegate int Add(int a, int b);

    }
}

通过如上两个例子,我们可以在C#中动态或者静态的调用C++写的代码了。

参考文章:http://www.cnblogs.com/Jianchidaodi/archive/2009/03/11/1407270.html#1473515

另外查看dll导出函数的小工具:http://www.dependencywalker.com/

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yaked19

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值