cja*_*ton 3 c typedef pthreads
我有一些嵌入式操作系统功能,我需要在linux机器上进行模拟.我被指示采取的方法是重载嵌入式操作系统功能并将它们包装在POSIX线程中,以便linux机器可以在单元测试期间处理嵌入式操作系统功能等等.
用于创建新线程的嵌入式OS函数是:
OSCreateTask(OStypeTFP functionPointer, OSTypeTcbP taskId, OStypePrio priority)
我需要将该OStypeTFP类型转换为pthread_create期望的void函数指针:( void * (*)(void *)编译器告诉我它的期望)
我希望创建一个我可以使用它的typedef:
typedef void (*OStypeTFP)(void);
// Function to run task/thread in
void taskFunction(void) { while(1); }
// Overloaded Embedded OS function
void OSCreateTask(OStypeTFP tFP, OStypeTcbP tcbP, OStypePrio prio)
{
pthread_attr_t threadAttrs;
pthread_t thread;
pthread_attr_init(&threadAttributes);
pthread_create(&thread, &threadAttributes, &tFP, NULL);
}
// Creates a task that runs in taskFunction
OSCreateTask (taskFunction, id, prio);
Run Code Online (Sandbox Code Playgroud)
但编译器抱怨pthread_create期望functionPointer的类型void (**)(void)void * (*)(void *)
我是否需要以某种方式更改我的typedef,还是需要进行类型转换?都?
你需要一个适配器功能:
typedef void (*OStypeTFP)(void);
// Function to run task/thread in
void taskFunction(void) { while(1); }
void *trampoline(void *arg)
{
OStypeTFP task = (OStypeTFP)arg;
task();
return NULL;
}
// Overloaded Embedded OS function
void OSCreateTask(OStypeTFP tFP, OStypeTcbP tcbP, OStypePrio prio)
{
pthread_attr_t threadAttrs;
pthread_t thread;
pthread_attr_init(&threadAttrs);
pthread_create(&thread, &threadAttrs, trampoline, tFP);
}
// Creates a task that runs in taskFunction
OSCreateTask (taskFunction, id, prio);
Run Code Online (Sandbox Code Playgroud)
当然,只有当系统允许强制转换void *为函数指针时,它才是安全的.但由于我们处于POSIX环境 - 它应该没问题.