1. 程式人生 > >vs2010 建立和C#使用動態連結庫(dll)

vs2010 建立和C#使用動態連結庫(dll)

一、VS 用 C++ 建立動態連結庫

Step 1:建立Win32 Console Application

本例中我們建立一個叫做“Test”的Solution。


Step 2:將Application Type設定為DLL

在接下來的 Win32 Application Wizard 的 Application Settings 中,將 Application type 從 Console application 改為 DLL:


Step 3:將方法暴露給DLL介面

現在在這個Solution中,目錄和檔案結構是這樣的:


編輯 Test.cpp 如下:

<span style="font-size:14px;">#include "stdafx.h"    
extern "C"  
{  
    _declspec(dllexport) int sum(int a, int b)  
    {  
        return a + b;  
    }  
} </span>

Step 4:編譯

直接編譯即可。

二、在C#中通過P/Invoke呼叫Test.dll中的sum()方法

P/Invoke很簡單。請看下面這段簡單的C#程式碼:

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

namespace CSharpusedll
{
    class Program
    {
        [DllImport("Test.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int sum(int a, int b);
        //加屬性CallingConvention = CallingConvention.Cdecl,否則發生錯誤“託管的PInvoke簽名與非託管的目標籤名不匹配”
        static void Main(string[] args)
        {
            int result = sum(2, 3);
            Console.WriteLine("DLL func execute result: {0}", result);
            Console.ReadLine();
        }
    }
}
編譯並執行這段C#程式,執行時別忘了把Test.dll拷貝到執行目錄(Debug)中。

也可加EntryPoint屬性,這樣提供一個入口,以便C#裡面可以用不同於dll中的函式名Sum。。

<span style="font-size:14px;">   [DllImport("Test.dll", EntryPoint = "sum")]
        private static extern int Sum(int a, int b);</span>