C#調用DLL庫的方法


  最近工作需要使用C#調用DLL,公司代碼不能公開就轉載加一些自己的筆記記錄一下。使用軟件VS2008和VS2017。

1 C#靜態調用DLL

1.1  建立VC工程CppDemo,建立的時候選擇Win32 Console(dll),選擇Dll。

1.2  在DllDemo.cpp文件中添加這些代碼。

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

1.3 編譯工程。

1.4 建立新的C#工程,選擇Console應用程序,建立測試程序InteropDemo
1.5 在Program.cs中添加引用:using System.Runtime.InteropServices;

1.6 在pulic class Program添加如下代碼:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;   // 用 DllImport 需用此 命名空間

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();
        }
    }
}    
View Code

 

2 C#動態調用DLL

在第一節中,講了靜態調用C++動態鏈接,由於Dll路徑的限制,使用的不是很方便,C#中我們經常通過配置動態的調用托管Dll,例如常用的一些設計模式:Abstract Factory, Provider, Strategy模式等等,那么是不是也可以這樣動態調用C++動態鏈接呢?只要您還記得在C++中,通過LoadLibrary, GetProcess, FreeLibrary這幾個函數是可以動態調用動態鏈接的(它們包含在kernel32.dll中),那么問題迎刃而解了,下面我們一步一步實驗

2.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);
    }
}
View Code

2.2 使用NativeMethod類動態讀取C++Dll,獲得函數指針,並且將指針封裝成C#中的委托。原因很簡單,C#中已經不能使用指針了,如下          
            int hModule = NativeMethod.LoadLibrary(@"c:"CppDemo.dll");

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

詳細請參見代碼 

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)
        {
            //1. 動態加載C++ Dll
            int hModule = NativeMethod.LoadLibrary(@"c:\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);

    }
}
View Code

 

3 注意事項:

3.1 使用靜態調用時必須將DLL文件和相關配置文件放於C#可執行文件同一部木之下,否則會報錯;

3.2 在C#中使用DllImport必須添加   using System.Runtime.InteropServices;

3.3 C#調用DLL時需要將 Properties中平台目標 改為和生成DLL中平台一致。(一般生成dll都是Win32,所以平台目標要改為X86。)                                                    

  

 

4 數據類型問題

因為在C#中部使用非安全是沒有指針數據類型,而一般使用C或C++制作的DLL,DLL中函數的參數列表會有指針類型,調用是就必須要解決或了解這一部分知識——互操作數。

4.1 C#互操作性入門系列(一):C#中互操作性介紹

4.2 C#互操作性入門系列(二):使用平台調用調用Win32 函數

4.3 C#互操作性入門系列(三):平台調用中的數據封送處理

4.4 C#互操作性入門系列(四):在C# 中調用COM組件

 

轉載鏈接:

1) https://www.cnblogs.com/Jianchidaodi/archive/2009/03/09/1407270.html

 2)  https://www.cnblogs.com/zhili/archive/2013/01/14/NetInterop.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM