C++生成dll提供给C#和C++本身调用

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());
        }
    }
}

 有兴趣的朋友可以尝试一下。

猜你喜欢

转载自blog.csdn.net/Bamboo265925/article/details/82077807