C 如何将具有参数的函数指针作为另一个函数的参数传递?
如您所见,我想将函数C 如何将具有参数的函数指针作为另一个函数的参数传递?,c,C,如您所见,我想将函数send_message传递给pthread_create,但我不知道如何传递它的参数。如何做到这一点 pthread_create(&t_write, NULL, send_message, NULL); // how to specify argument of the send_message? void *send_message(void *sockfd){ char buf[MAXLEN]; int *fd = (int *)sockf
send_message
传递给pthread_create
,但我不知道如何传递它的参数。如何做到这一点
pthread_create(&t_write, NULL, send_message, NULL); // how to specify argument of the send_message?
void *send_message(void *sockfd){
char buf[MAXLEN];
int *fd = (int *)sockfd;
fgets(buf, sizeof buf, stdin);
if(send(*fd, buf, sizeof buf, 0) == -1){
printf("cannot send message to socket %i\n", *fd);
return (void *)1;
}
return NULL;
}
简短回答:只需将参数作为第四个参数传递给
pthread\u create
详细回答:pthread\u create
的定义如下(根据手册页):
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
第三个参数的含义可以用cdecl
解码:
cdecl> explain void *(*start_routine) (void *)
declare start_routine as pointer to function (pointer to void) returning pointer to void
如您所见,它需要一个指向函数的指针,该函数接受void*
并返回void*
。幸运的是,这正是你所拥有的。根据pthread\u create
的手册页:
新线程通过调用start_routine()
开始执行arg
作为start\u routine()
的唯一参数传递
您是否查看过库函数
qsort()
以了解传递函数参数是如何实现的?