版权声明:本文为博主原创文章,未经博主允许不得转载。
调用外部已编译好的C语言模块,传递参数并将结果返回打印出来。
C语言模块代码:
- /**********Test.c**********/
- /**********用gcc编译后生产那个的可执行文件test放在..../invokec/C/目录下**********/
- #include <stdio.h>
- int main(int argc,char *argv[])
- {
- printf("Hello,I am a C program!\n");
- printf("now,I am invoked by a program called Qt!\nfollowing are the parameters that Qt sends to me:\n");
- printf("%s\n",argv[0]);
- printf("%s\n",argv[1]);
- printf("%s\n",argv[2]);
- return 0;
- }
Qt代码:
- /********MyTest.h***********/
- #ifndef MYTEST_H_
- #define MYTEST_H_
- #include <QtGui/QWidget>
- #include <QtGui/QPushButton>
- class MyTest : public QWidget
- {
- Q_OBJECT
- public:
- MyTest();
- ~MyTest();
- public slots:
- void invokeC();
- private:
- QPushButton *pb;
- };
- #endif
- /********MyTest.cpp**********/
- #include "MyTest.h"
- #include <QtCore/QProcess>
- #include <iostream>
- #include <QtCore/QTextStream>
- #include <QtCore/QIODevice>
- MyTest::MyTest()
- :QWidget()
- {
- this->setGeometry(0,0,200,50);
- pb=new QPushButton("点击调用C程序",this);
- pb->setGeometry(0,0,200,50);
- connect(pb,SIGNAL(clicked()),this,SLOT(invokeC()));
- }
- MyTest::~MyTest()
- {
- }
- void MyTest::invokeC()
- {
- QProcess *process=new QProcess();
- QStringList str;
- str.clear();
- str << "a" << "b" ;
- process->start("../C/test",str);
- process->waitForStarted();
- process->waitForFinished();
- QByteArray qb=process->readAll();
- QString str22(qb);
- QTextStream cout(stdout);
- cout<<str22<<endl;
- }
- /***********Main.cpp************/
- /*******编译后放在...../invokeC/Qt/目录下************/
- #include <QtGui/QApplication>
- #include <QtCore/QTextCodec>
- #include "MyTest.h"
- int main(int argc,char *argv[])
- {
- QApplication a(argc,argv);
- QTextCodec *codec = QTextCodec::codecForLocale();
- QTextCodec::setCodecForCStrings(codec);
- a.setFont(QApplication::font());
- MyTest *mt=new MyTest;
- mt->show();
- return a.exec();
- }
运行结果: