1. 程式人生 > >編譯生成C++導出函數dll,並在C#工程中測試

編譯生成C++導出函數dll,並在C#工程中測試

lec ces 說明 cnblogs c# point article span targe

編譯生成過程:

1.建立dll工程

選擇新建visual C++的

技術分享

這兩個類型工程,都會出現下面界面,在這裏設置生成dll:

技術分享

2.設置項目:

項目屬性中設置:

技術分享

3.相關代碼:

由於項目的名稱是"TestCPPDLL",因此,會自動生成TestCPPDLL.h和TestCPPDLL.cpp兩個文件,.h文件是要導出內容的聲明文件,為了能清楚的說明問題,我們將TestCPPDLL.h和TestCPPDLL.cpp兩個文件中的所有內容都刪除,然後在TestCPPDLL.h中添加如下內容:

頭文件:

#define TESTCPPDLL_API __declspec(dllexport)
EXTERN_C TESTCPPDLL_API 
int __stdcall Add(int a, int b);

源文件:

TESTCPPDLL_API int __stdcall Add(int a, int b)
{
    return a + b;
}

測試過程如下:

新建一個C#空工程項目,修改生成的main文件:

1.添加

using System.Runtime.InteropServices;

2.在靜態方法中添加:

[DllImport(@"G:/VS13_Project/TestCPPDLL/Release/TestCPPDLL.dll", EntryPoint = "Add")]
extern static int Add(int a, int b);

具體如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Runtime.InteropServices; //加上這行

namespace testC
{
    class Program
    {
        [DllImport(@"G:/VS13_Project/TestCPPDLL/Release/TestCPPDLL.dll", EntryPoint = "Add")]
        
extern static int Add(int a, int b); static void Main(string[] args) { int c = Add(1, 2); Console.Write(c); Console.Read(); } } }

參考:http://jingyan.baidu.com/article/67508eb43f91869cca1ce49c.html

編譯生成C++導出函數dll,並在C#工程中測試