C#调用mingw编译出来的动态链接库实例(建议使用MSVC编译的)

一般情况C#调用MSVC编译出来的C/C++动态库,不会有太大问题,但是如果是mingw编译出来的呢?

答案是不确定的,得取决于你如何编译!

今天在这用一个例子实现C# 调用mingw编译出来的动态链接库

编译库:

qt的pro文件(因为qt用习惯了)

#-------------------------------------------------
#
# Project created by QtCreator 2019-08-30T11:05:01
#
#-------------------------------------------------
 
QT       -= core gui
CONFIG += dll
TARGET = MyTestDll
TEMPLATE = lib
 
DEFINES += MYTESTDLL_LIBRARY
 
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
 
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
 
SOURCES += \
        mytestdll.cpp
 
HEADERS += \
        mytestdll.h \
        mytestdll_global.h 
 
unix {
    target.path = /usr/lib
    INSTALLS += target
}
 
DISTFILES += \
    lib.def
 
 
win32 {
    win32-g++{
        QMAKE_LFLAGS += -static
    }
}
头文件

#ifndef MYTESTDLL_H
#define MYTESTDLL_H
 
#include "mytestdll_global.h"
 
extern"C"    //此处代表按c风格编译,避免c++独特的编译方式,是的函数名发生改变
{
#define DLLMODLE_FUNCTIONTYPE __declspec(dllexport)    //导出函数,声明dll的导出函数时,编译此处
//声明导出函数
DLLMODLE_FUNCTIONTYPE int add()
 
{
    return 5;
 
}
 
#endif // MYTESTDLL_H
//def文件,这是关键,如果没有的话,msvc编译出来的C#可以调用,但mingw的不行

extern"C"    //此处代表按c风格编译,避免c++独特的编译方式,是的函数名发生改变
{
//声明导出函数
    int __stdcall add();
}
 

C#调用库的方法

namespace WindowsFormsApplication1
{
 
 
    public partial class Form1 : Form
    {
        [DllImport("MyTestDll.dll")]
        public static extern int add();
        //[DllImport("ParaConfig.dll")]
        //public static extern int createConfigData();
        
        public Form1()
        {
            InitializeComponent();
            
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            /*
            string src = "C:\\Users\\lenovo\\Desktop\\DataDll\\threeGrade.json";
            string dst = "C:\\Users\\lenovo\\Desktop\\DataDll\\outputJson.json";
            int bb = createConfigData();
             * */
            int bb = add();
        }
    }
}
 

猜你喜欢

转载自blog.csdn.net/u011555996/article/details/129073235
今日推荐