一、新建一個解決方案,並在解決方案下添加一個.netframework的項目,命名為FrameworkConsoleTest。再添加一個C++的動態鏈接庫DLL項目,命名為EncryptBase。
二、將C++項目EncryptBase設為按64位生成部署。(如果你電腦是32位系統就設x86,是64位系統就設x64)
三、將解決方案設為“當前選定內容”啟動。
四、在EncryptBase頭文件,右鍵--添加--新建項,添加一個EncryptBase.h的頭文件。
1、添加以下代碼:
#ifndef _ENCRYPTBASE_H //定義_ENRYPTBASE_H宏,是為了防止頭文件的重復引用 #define _ENCRYPTBASE_H #ifdef __cplusplus //而這一部分就是告訴編譯器,如果定義了__cplusplus(即如果是cpp文件, extern "C" { //因為cpp文件默認定義了該宏),則采用C語言方式進行編譯 #endif #ifdef DLL_EXPORTS #define DLL_EXPORTS __declspec(dllexport) #else #define DLL_EXPORTS __declspec(dllimport) #endif DLL_EXPORTS int Sum(int value1, int value2); #ifdef __cplusplus } #endif #endif // !_ENCRYPTBASE_H
2、添加后如圖所示:
五、在FrameworkConsoleTest項目的Program修改為以下代碼。
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace FrameworkConsoleTest { class Program { [DllImport("EncryptBase.dll", CallingConvention = CallingConvention.Cdecl)] static extern int Sum(int value1, int value2); static void Main(string[] args) { int sumValue = Sum(1, 2); Console.WriteLine("sumValue:"+sumValue); } } }
修改后如圖所示:
六、在EncryptBase項目,右鍵--屬性--生成事件--生成后事件--命令行--編輯。設置生成后事件之后,編輯EncryptBase項目就不用每次將bin的dll復制到FrameworkConsoleTest項目了。
2、輸入以下內容:
copy "$(OutputPath)$(TargetFileName)" "$(SolutionDir)FrameworkConsoleTest\bin\Debug"
copy "$(OutputPath)EncryptBase.pdb" "$(SolutionDir)FrameworkConsoleTest\bin\Debug"
3、設置后如下所示:
4、生成EncryptBase項目。
六、在FrameworkConsoleTest,右鍵屬性--生成--取消勾選"首選32位"。
七、運行。
在FrameworkConsoleTest項目,組合按Ctrl+F5,可顯示調用結果。如下圖所示。
八、文件已上傳,可點擊下載。
https://files.cnblogs.com/files/suterfo/AuthorizationTest(Demo1).rar