gpt4 book ai didi

c - 将 void*(*)(void*) 类型转换为 void(*)(void)

转载 作者:太空狗 更新时间:2023-10-29 15:16:29 29 4
gpt4 key购买 nike

作为作业的一部分,我正在尝试创建一个用户级线程库,如 pthreads。

为了处理线程之间的上下文切换,我使用了“swapcontext”函数。在使用它之前,我必须使用“makecontext”函数创建一个上下文。 “makecontext”需要一个返回类型为 void 和参数类型为 (void) 的函数指针。

而线程函数的类型必须是 void* thread_func (void*)

有没有办法进行类型转换?或者是否有其他方法可以在用户级别进行上下文切换?

最佳答案

通过将函数的地址转换为不同的原型(prototype)并通过结果指针调用它来调用具有不兼容原型(prototype)的函数是非法的:

void *my_callback(void *arg) { ... }

void (*broken)(void *) = (void (*)(void *)) my_callback;
broken(some_arg); // incorrect, my_callback returns a `void *`

您可以做的是将您自己的回调传递给 makecontext,它将调用 thread_func 并忽略其返回值。仅用于调用另一个函数的小函数有时称为 trampoline。 .

/* return type is compatible with the prototype of the callback received
by makecontext; simply calls the real callback */
static void trampoline(int cb, int arg)
{
void *(*real_cb)(void *) = (void *(*)(void *)) cb;
void *real_arg = arg;
real_cb(real_arg);
}

int my_pthread_create(void *(*cb)(void *), void *arg)
{
ucontext_t *ucp;
...
/* For brevity treating `void *` as the same size as `int` -
DO NOT USE AS-IS.
makecontext exposes an annoyingly inconvenient API that only
accepts int arguments; correct code would deconstruct each
pointer into two ints (on architectures where pointer is
larger than int) and reconstruct them in the trampoline. */
makecontext(ucp, trampoline, 2, (int) cb, (int) arg);
...
}

对于奖励积分,您可以修改蹦床以将回调函数返回的 void * 值存储在堆栈上,并让您的 pthread_join() 检索它.

关于c - 将 void*(*)(void*) 类型转换为 void(*)(void),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14530109/

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