我编写了以下代码来处理Linux上的操纵杆:
static int fd;
int joystick_init(void)
{
struct js_event event;
if((fd = open("/dev/input/js1", O_RDONLY | O_NONBLOCK)) == -1)
return ERROR;
//ignore all init events
while(read(fd, &event, sizeof(struct js_event)) == sizeof(struct js_event)){
}
return SUCCESS;
}
void joystick_end(void)
{
close(fd);
}
const struct js_event *joystick_get_event(void)
{
static struct js_event event;
if(read(fd, &event, sizeof(struct js_event)) == sizeof(struct js_event))
return &event;
return NULL;
}
以下内容打印事件:
void joy_input(const struct js_event *event)
{
switch(event->type){
case JS_EVENT_BUTTON:
printf("button number = %d\n", event->number);
break;
case JS_EVENT_AXIS:
printf("axis number = %d\n", event->number);
break;
}
printf("event time = %d\n", event->time);
printf("event value = %d\n", event->value);
printf("event type = %d\n", event->type);
puts("joy_input called");
}
这是每次按下按钮时打印的内容:
活动时间= 6348112
事件值= 0
事件类型= 0
joy_input调用
问题是什么?为什么不报告JS_EVENT_BUTTON
或JS_EVENT_AXIS
?为什么时间不变?
修改
//void * can't point to functions
typedef struct Joystick_Listener {
void (*cb)(const struct js_event *event);
} Joystick_Listener;
static void dispatch_joy_events(Node *node, void *arg)
{
Joystick_Listener *listener = node->content;
listener->cb(arg);
}
void video_and_input_run(void)
{
const struct js_event *event;
while(1){
/* ... */
//Call joystick listeners
pthread_mutex_lock(&joy_listener_lock);
while((event = joystick_get_event()) != NULL)
list_iterate_arg(&joy_listener, dispatch_joy_events, &event);
pthread_mutex_unlock(&joy_listener_lock);
/* ... */
}
}
void list_iterate_arg(const List *list, void(*function)(Node*, void *), void *arg)
{
Node *next; //store in case the node changes
for(Node *ite = list->first; ite != NULL; ite = next){
next = ite->next;
function(ite, arg);
}
}
答案 0 :(得分:0)
愚蠢的错误,我传递了event
的地址,但它已经是事件的指针,而不是事件本身,所以没有任何意义。
void video_and_input_run(void)
{
const struct js_event *event;
while(1){
/* ... */
//Call joystick listeners
pthread_mutex_lock(&joy_listener_lock);
while((event = joystick_get_event()) != NULL)
list_iterate_arg(&joy_listener, dispatch_joy_events, event);
pthread_mutex_unlock(&joy_listener_lock);
/* ... */
}
}