利用C++創建DLL並C#調用


日期:2018年11月26日

環境:window 10,VS2015 community

一、利用C++創建DLL

  1.新建項目;

  

  

  2.打開CreateDLL.cpp文件,並輸入測試代碼

  

 1 #include "stdafx.h"
 2 
 3 int __stdcall Add(int a, int b)
 4 {
 5     return a + b;
 6 }
 7 
 8 int __stdcall Sub(int a, int b)
 9 {
10     return a - b;
11 }
DLL Test Code

  3.給工程添加一個.def文件,並在該文件中插入以下代碼;

1 LIBRARY CreateDLL
2 EXPORTS
3 Add @1,
4 Sub @2,
def Code

  注意這里的CreateDLL是工程名如果不同則應用程序連接庫時會發生連接錯誤!

  其中LIBRARY語句說明該def文件是屬於相應DLL的,EXPORTS語句下列出要導出的函數名稱。我們可以在.def文件中的導出函數后加 @n,如Add@1,Sub@2,表示要導出的函數順序號,在進行顯式連時可以用到它。該DLL編譯成功后,打開工程中的Debug目錄,同樣也會看到 CreateDLL.dll和CreateDLL.lib文件。

二、使用C#調用DLL

  1.在新建的C#工程中插入以下代碼;

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Runtime.InteropServices;
 7 
 8 namespace AcmeCollections
 9 {
10     class Program
11     {
12         [DllImport(@"C:\Users\xxxxx\Desktop\study\CreateDLL\Debug\CreateDLL.dll")]//DLL的位置
13         public static extern int Add(int a, int b);
14 
15         [DllImport(@"C:\Users\xxxxx\Desktop\study\CreateDLL\Debug\CreateDLL.dll")]
16         public static extern int Sub(int a, int b);
17         static void Main(string[] args)
18         {
19             long ans;
20             string str;
21             
22             ans = Add(9, 7);
23             str = Convert.ToString(ans);
24             Console.WriteLine(str);
25             ans = Sub(9, 7);
26             str = Convert.ToString(ans);
27             Console.WriteLine(str);
28             Console.ReadLine();
29         }
30     }
C# Main Code

  2.運行結果;

  

 

參考鏈接:http://www.cnblogs.com/daocaoren/archive/2012/05/30/2526495.html


免責聲明!

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



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