C#调用Qt写的dll@Qt5.12.0+VS2017

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/iamohenry/article/details/80407930

 

C#调用QT的动态库,只要一 new QWidget的类,就会报错。在网上查找资料后找到以下解决方法。

原文链接:https://blog.csdn.net/iamohenry/article/details/80407930

解决方法:

在需要导出的方法外加上

     int argc = 0;
    QApplication a(argc, NULL);
//    Dialog *dlg = new Dialog();
 //   dlg->show();

//DO YOURSELF
    return a.exec();

即可。

 

以下是引用@ iamohenry的文章中的demo:

代码如下:

Qt dll:

qtui.pro:

TEMPLATE = lib

CONFIG        += dll
SOURCES         = main.cpp \
    dialog.cpp
TARGET         = qtui
DLLDESTDIR   = $$[QT_INSTALL_PREFIX]/bin
include(../../src/qtwinmigrate.pri)
FORMS += \
    dialog.ui
HEADERS += \
    dialog.h

 

头文件:dialog.h

#ifndef DIALOG_H

#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
    Q_OBJECT
public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
private slots:
    void on_m_pbCalc_clicked();
private:
    Ui::Dialog *ui;
};
#endif // DIALOG_H
cpp:

#include "dialog.h"

#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}
Dialog::~Dialog()
{
    delete ui;
}
void Dialog::on_m_pbCalc_clicked()
{
    int add1 = ui->m_lE1->text().toInt();
    int add2 = ui->m_lE2->text().toInt();
    int sum = add1+add2;
    QString strSum;
    strSum.setNum(sum);
    ui->m_lbSum->setText(strSum);
    ui->m_lEsum->setText(strSum);
}
main.cpp


#include <QMessageBox>
#include <windows.h>
#include "dialog.h"
extern "C" __declspec(dllexport) int showDialog()
{
    int argc = 0;
    //char* argv[] = NULL;
    QApplication a(argc, NULL);
    Dialog *dlg = new Dialog();
    dlg->show();
    return a.exec();
}
//int main()
//{
//    Dialog *dlg = new Dialog();
//    dlg->show();
//    return 0;
//}
界面没有啥,就是三个文本框: 实现一个加法;

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;
using System.Windows;


namespace CSCallQtdll
{
    public partial class Form1 : Form
    {
        [DllImport("qtui.dll")]
        public static extern int showDialog();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            showDialog();
        }
    }
}


界面就一个按钮,把qtui.dll添加进项目就可以了;
————————————————
版权声明:本文为CSDN博主「iamohenry」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/iamohenry/article/details/80407930

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值