gpt4 book ai didi

c++ - linux c++ xlib,如何使用 XSaveContext 和 XFindContext(提供示例)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:36 43 4
gpt4 key购买 nike

对于某些窗口返回的XNextEvent(display,&e) 我需要访问这个窗口所属的类,在网络和书籍上进行了一些搜索之后, XSaveContextXFindContext看起来很有用,但我没有找到任何使用示例。那么让我们试试吧:

我有一个 class Metallica,当在 中调用 constructor 时,我想保存一个 Metallica object 的地址>X上下文 :

class Metallica{
private:
Window window;
int i;
.
.
public:
Metallica(...,int j, XContext *context){
.
.
i=j;
//XSaveContext(display, this->window, *context, this); // don't work
XSaveContext(display, this->window, *context, XPointer(this));
.
.
void MasterOfPuppet(){
cout << i << endl;
};
void FadeToBlack(){
cout << "OK" << endl;
};
};

};

所以现在在我的 xevent 循环中我想取回一个 Metallica 对象的地址,

// at the declaration area :
// XContext Metallica_Context;
// XPointer *XPointerToOneMetallicaObject;

XFindContext(display,
e.xany.window,
Metallica_Context,
XPointerToOneMetallicaObject );

Metallica *SandMan = (Metallica*)(*XPointerToOneMetallicaObject);

SandMan->FadeToBlack(); // no problem
SandMan->MasterOfPuppet(); // return a segmentation fault

所以我做错了什么,但是呢?

最佳答案

我发现我哪里错了,当我调用 XFindContext() 时,参数 e.xany.window 可以被“任何”窗口调用,所以即使没有创建通过 Metallica,然后调用 MasterOfPuppet() 做狗屎......所以我需要保护调用就是这样!

好吧,这是一个基本的(我不保护调用,但在这种情况下不做任何事情)工作代码(您可以使用此代码来查看 XContext 如何被使用,幸运的你......):

//g++ test.cc -lX11
#include<iostream>
#include<unistd.h>
#include<X11/Xlib.h>
#include<X11/Xutil.h>

Display *display;


class Metallica{
private:
Window window;
int i;

public:
Metallica(int j, XContext *context){
i=j;
this->window = XCreateSimpleWindow(display,DefaultRootWindow(display),100,100,100,100,0,0,0);
XSelectInput(display, this->window, ExposureMask|ButtonReleaseMask|KeyReleaseMask);
XMapWindow(display,this->window);
XSaveContext(display, this->window, *context, XPointer(this));
};
void MasterOfPuppet(){
std::cout << i << std::endl;
};
void FadeToBlack(){
std::cout << "ok" << std::endl;
};
};

int main(){
XContext Metallica_context;
XPointer *XPointerToOneMetallicaObject;
XEvent e;
int DoNotStop=1;

display = XOpenDisplay(0);

Metallica OneMetallicaObject(2,&Metallica_context);
Metallica *SandMan;

while(DoNotStop){
XNextEvent(display, &e);
switch(e.type){
case Expose : XFlush(display); break;
case ButtonRelease : XFindContext(display,e.xany.window,Metallica_context,XPointerToOneMetallicaObject);
SandMan = (Metallica*)(*XPointerToOneMetallicaObject);
SandMan->MasterOfPuppet();
break;
case KeyRelease : DoNotStop=0; break;
}
}

return 0;
}

关于c++ - linux c++ xlib,如何使用 XSaveContext 和 XFindContext(提供示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054125/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com