QT应用编程: windows下QT调用COM组件

一、环境介绍

操作系统: win10 64位

QT版本: 5.12.6

Visual Studio IDE 版本:  2017

示例工程下载链接:  https://download.csdn.net/download/xiaolong1126626497/14919797

二、创建COM组件

为了方便测试,我这里使用QT来创建COM组件,再由QT自己调用。 理论上任何语言生成的COM组件调用流程应该都是一样的。

QT创建COM的方法看这里:

(1)VS2017下使用QT生成COM组件:      https://blog.csdn.net/xiaolong1126626497/article/details/112556866

(2) QtCreate下生成COM组件:  https://blog.csdn.net/xiaolong1126626497/article/details/112550412

当前创建COM组件的工程我是使用VS2017+QT插件的方式生成的。

为了方便注册可以在目录下写个脚本:

  安装代码:

cd /d %~dp0
@regsvr32 ActiveQtServer_vs2017.dll
@exit

  卸载代码:

cd /d %~dp0
@regsvr32 /u ActiveQtServer_vs2017.dll
@exit

三、QtCreate里创建工程调用COM组件

3.1 创建工程

3.2 编写测试代码

#include <QApplication>
#include <QAxObject>
#include <QDebug>
#include <QFile>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

     QAxObject *mpAxObj;
    mpAxObj = new QAxObject();

    //指定调用的COM组件类ID,这个ID要填正确.
    mpAxObj->setControl("{fe8bb3a1-998e-4318-b4ee-4263a1cc06a2}");

    //导出支持调用的函数接口
    QString DOC = mpAxObj->generateDocumentation();
    QFile outFile("com_function.html");
    outFile.open(QIODevice ::ReadWrite|QIODevice ::Text);
    QTextStream TS(&outFile);
    TS<<DOC<<endl;

    //调用COM组件函数接口: 获取版本号
    QString result = mpAxObj->dynamicCall("VersionNumber()").toString();
    qDebug()<<"VersionNumber:"<<result;

    //调用COM组件函数接口: 求和计算
    QVariantList params ={100,200};
    int sum_val = mpAxObj->dynamicCall("sum(int, int)", params).toInt();
    qDebug()<<"sum:"<<sum_val;

    //调用COM组件函数接口: 显示界面
    mpAxObj->dynamicCall("show()");

    return a.exec();
}

3.3 工程pro文件

QT       += core gui
QT += axcontainer
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked 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 it uses 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 += \
    main.cpp

HEADERS +=

FORMS +=

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

3.4 运行测试

说明: 如何调用运行失败,记得把COM组件dll依赖的所有文件拷贝到现在测试程序运行的目录下,防止找不到依赖文件运行失败。

猜你喜欢

转载自blog.csdn.net/xiaolong1126626497/article/details/112978956
今日推荐