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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章