這篇文章為使用 C++ 寫DLL可以在 C# 使用
這篇文章為使用 C++ 寫DLL可以在 C# 使用
這篇文章是使用 VS19
請先參閱:
1.這篇寫得非常棒推薦看: https://oblivious9.pixnet.net/blog/post/206689885-c%2B%2B-%E8%A3%BD%E4%BD%9Cdll%E7%B5%A6c%23%E4%BD%BF%E7%94%A8
2.(Common Language Runtime 編譯): https://docs.microsoft.com/zh-tw/cpp/build/reference/clr-common-language-runtime-compilation?view=msvc-160
3.vs2019 C++/CLI 或 C++/CX: https://blog.csdn.net/qq_33435149/article/details/110289698
先設定出專案
檔案名字為: MyDLL_CPlusforCSharp1
設定為:DLL檔案
先設定H檔: ForCSharpCallDefine.h
ForCSharpCallDefine.h 檔案寫入
#pragma once
class Addition
{
public:
Addition();//預設的空建構子
int Add_test(int a, int b);//加法
};
先設定CPP檔: ForCSharpCallImplement.cpp
ForCSharpCallImplement.cpp 檔案寫入
#include "ForCSharpCallDefine.h"
Addition::Addition()
{
}
int Addition::Add_test(int a, int b)
{
return a + b;
}
先設定CPP檔: ForExternCall.cpp
ForExternCall.cpp 檔案寫入
#ifdef FORCSHARPCALL_EXPORTS
#define FORCSHARPCALL_API __declspec(dllexport)
#else
#define FORCSHARPCALL_API __declspec(dllimport)
#endif
#include "ForCSharpCallDefine.h"
extern "C" FORCSHARPCALL_API int Add(int a, int b);
extern int Add(int a, int b)
{
Addition cal;
return cal.Add_test(a, b);
}
設定屬性:
組態屬性→進階→ common language runtime
C/C++→語言→ common language runtime
建置DLL檔案
接下來建立一個C#
建立一個加法的介面
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Test_CPlusforCSharp
{
public partial class Form1 : Form
{
[DllImport("MyDLL_CPlusforCSharp1.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
private static extern int add(int a, int b);
public Form1()
{
InitializeComponent();
}
private void button_Add_Click(object sender, EventArgs e)
{
textBox_X1addX2.Text
= (int.Parse(textBox_X1.Text) + int.Parse(textBox_X2.Text)).ToString();
}
}
}
測試看看