C#呼び出しmingwコンパイルされたダイナミックリンクライブラリ

2711 ワード

一般的に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();
        }
    }
}