C# 調用 C++編譯的Dll

1.創建一個C++動態鏈接庫(通過VS圖形引導界面)
2.添加C++類
CallC.cpp

// CallC.cpp : 定義 DLL 應用程序的導出函數。
//

#include "stdafx.h"

extern "C" __declspec(dllexport) int Add(int a , int b)
{
    return a+b;
}

extern "C" __declspec(dllexport) int Sub(int a ,int b)
 {
     return a-b;
 }

3.在相同解決方案下創建一個C#工程(WinForm就可以),再添加一個調用C++類庫的函數轉換類,
CallCFunc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    class CallCFunc
    {
        [DllImport("CallC.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
        public static extern int Add(int a,int b);
    }
}

注:需要將C++編譯好的Dll 拷貝到C#的bin/Debug下(或Release),也可以一次性設置好C++類庫的Dll 輸出路徑,設置方式如下:
右鍵項目->屬性->屬性配置->常規->輸出目錄。

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