標籤:tool 函數 bottom rda clr width 程式 define using
第一次用C#調用C/C++產生的DLL檔案,感覺有點新鮮,事實上僅僅是實現了執行在公用語言執行庫 (CLR) 的控制之外的“Unmanaged 程式碼”(執行在公用語言執行庫(CLR)的控制之中的代碼碼稱為“Managed 程式碼“)的東西,如何運用在託管下的非託管呢?如今給感興趣的剛開始學習的人簡單地寫一個實現的全過程吧(有什麼問題千萬別笑):
1.用VS2008選擇其他語言(C++)建立一個控制台應用程式命名為Mydll1,然後選擇應用程式類型為DLL,確定
項目
在標頭檔 stdafx.h 下加入例如以下聲明:
#define LIBEXPORT_API extern "C" __declspec(dllexport)
LIBEXPORT_API int Add(int a, int b);
在MyDll.cpp中實現這個函數:
#include "stdafx.h"
int Add(int a,int b)
{
return a+b;
}
注意假設實現的方法是聲明在其他標頭檔裡的,一定要 加#include "xxx.h" 來引用這個聲明了這個函數標頭檔。
產生MyDll.dll和MyDll.lib。
2.在Visual C# .net中引用dll檔案
建立Visual C#控制台應用程式命名為TestImportDll;
將MyDll.dll和MyDll.lib複製到可運行檔案檔案夾下():
在Praogram.cs中加入引用using System.Runtime.InteropServices;
按例如以下方式聲明一個將要引用MyDll.dll中函數的類:
class test
{
//[DllImport("..\\..\\lib\\CppDemo.dll")]
//public static extern void Function();
//[DllImport("..\\..\\lib\\CppDemo.dll")]
//public static extern int Add(int i, int j);
[DllImport("..\\..\\Lib\\Mydll1.dll")]
public static extern int Add(int a, int b);
}
最後在Main函數中調用這個類輸出結果:
static void Main(string[] args)
{
Console.WriteLine("result: " + test.Add(2, 3).ToString());
Console.ReadLine();
}以下是Program.cs的代碼:END():
程式C++ to C#互動