C++生成dll提供給C#和C++本身呼叫
阿新 • • 發佈:2018-12-10
1.專案整體結構如下:
2.定義標頭檔案dllpic.h
#ifndef DllTest_H_ #define DllTest_H_ #ifdef MYLIBDLL #define MYLIBDLL extern "C" _declspec(dllimport) #else #define MYLIBDLL extern "C" _declspec(dllexport) #endif MYLIBDLL int _stdcall Add(int plus1, int plus2); MYLIBDLL int _stdcall Minus(int plus1, int plus2); //MYLIBDLL int Add(int plus1, int plus2); //You can also write like this: //extern "C" { //_declspec(dllexport) int Add(int plus1, int plus2); //}; #endif
3.編寫原始檔dllpic.cpp,程式碼包含加減運算測試,方便學習。
#include<iostream> #include<string> #include<sstream> #include"dllpic.h" using namespace std; #include "opencv2/opencv.hpp" using namespace cv; int _stdcall Add(int n1, int n2) { return (n1 + n2); } int _stdcall Minus(int n1, int n2) { return (n1 - n2); }
4.編寫dllpic.def,將函式方法開放給外部程式呼叫
LIBRARY dllpic
EXPORTS Add Minus
5.C++自身呼叫測試程式碼:和普通的dll使用一樣,專案屬性包含目錄新增***.h所在目錄,庫目錄新增***.dll和***.lib所在目錄,連結器-輸入-附加依賴項要新增***.lib即可;測試程式碼。
// dllTest.cpp : 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include<iostream> #include "dllpic.h" using namespace std; int main() { int a = 2; int b = 4; cout << Add(a, b) << endl; // char c; cin >> c; return 0; }
6.C#測試程式碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class Form1 : Form
{
[DllImport("jiaozhengPic.dll")]
private extern static int Add(int n1, int n2);
[DllImport("jiaozhengPic.dll")]
private extern static int Minus(int n1, int n2);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int a1 = 10;
int a2 = 12;
int addH;
addH = Add(a1, a2);
MessageBox.Show(addH.ToString());
addH=Minus(a1, a2);
MessageBox.Show(addH.ToString());
}
}
}
有興趣的朋友可以嘗試一下。