使用linux共享内存机制完成Qt与应用程序之间的通信,Qt加载制作自己的共享内存静态库
首先完成共享内存小程序,源码:
- /*shm.h*/
- #ifndef SHM_H
- #define SHM_H
- #ifdef __cplusplus
- extern "C"{
- #endif
- typedef struct {
- char name[4];
- int age;
- }people;
- people* initshm(void);
- void *Create_sharememory(const char *filename,unsigned int SizeCount);
- void close_sharememory(void *pshare);
- int get_age(people *p);
- void set_age(people *p,int age);
- #ifdef __cplusplus
- }
- #endif
- #endif
- /*shm.cpp*/
- #include <cstdlib>
- #include <cstdio>
- #include <cstring>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/shm.h>
- #include <pthread.h>
- #include "shm.h"
- const char *shmfile="/home/xjf/Desktop/pro/1.txt";
- people* initshm(void)
- {
- people *p = (people *)Create_sharememory(shmfile,sizeof(people));
- if(p == NULL)
- printf("create sharememory failed!\n");
- return p;
- }
- void *Create_sharememory(const char *filename,unsigned int SizeCount)
- {
- int shm_id,fd;
- key_t key;
- void *pshare;
- const char *path=filename;
- if((fd=open(path,O_RDWR|O_CREAT))<0)
- {
- perror("opne");
- return 0;
- }
- close(fd);
- key=ftok(path,10);
- if(key==-1)
- {
- perror("ftok error\n");
- return 0;
- }
- if((SizeCount%2)!=0)SizeCount++;
- shm_id = shmget(key,SizeCount,IPC_CREAT);
- if(shm_id==-1)
- {
- perror("shmget error\n");
- return 0;
- }
- pshare = shmat(shm_id,NULL,0);
- if(pshare==NULL)
- {
- return 0;
- }
- return pshare;
- }
- void close_sharememory(void *pshare)
- {
- if(shmdt(pshare)==-1)
- perror("detach error");
- }
- int get_age(people *p)
- {
- return p->age;
- }
- void set_age(people *p,int age)
- {
- p->age=age;
- }
把shm.cpp制作成静态库libshm,命令如下
g++ -c shm.cpp //生成shm.o链接文件
ar cr libshm.a shm.o //生成静态库
再编写main.cpp函数完成静态库和头文件的调用
- /*main.cpp*/
- #include <cstdlib>
- #include <cstdio>
- #include <cstring>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/shm.h>
- #include <pthread.h>
- #include "shm.h"
- int main()
- {
- int age;
- people *t;
- t=initshm();
- set_age(t,20);
- age = get_age(t);
- printf("%d\n",age);
- return 0;
- }
编译:g++
-o shm main.cpp -L. -lshm
运行:./shm
运行成功。
使用Qt程序加载前面制作的静态库
- #include "mainwindow.h"
- #include "ui_mainwindow.h"
- #include "shm.h"
- MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow)
- {
- ui->setupUi(this);
- ui->label->setText("nihao");
- int age;
- people *t;
- t=initshm();
- set_age(t,20);
- age = get_age(t);
- ui->label->setText(QString::number(age));
- }
- MainWindow::~MainWindow()
- {
- delete ui;
- }
然后在pro工程文件中加入LIBS
+=
-L
./
-lshm这样qt就能加载非官方的静态库了。
参考资料:
http://www.cnblogs.com/hicjiajia/archive/2012/05/17/2506632.html
http://blog.163.com/hitperson@126/blog/static/130245975201151552938133/
http://blog.csdn.net/chenjin_zhong/article/details/6147858
阅读(8367) | 评论(0) | 转发(1) |