2012-10-17 67 views
0

我试图使用具有这样定义的线程启动功能的线程库:如何将一个函数指针传递给这个函数

int vg_thread_create(VGThreadFunction func, 
    void *arg, 
    VGThreadDescriptor *tid, 
    void *stack, 
    size_t stack_size, 
    long priority, 
    int flags); 

而且VGThreadFunction是下面的typedef:

typedef void* (*VGThreadFunction) (void*) 

为了论证的缘故,我有这样的功能:

void doit() { 
    cout << "Woohoo printing stuff in new thread\n"; 
} 

这个签名函数不是void * func(void *) - 我是否被迫使用这样的函数签名?

如果我尝试:

VGThreadFunction testfunc = &doit; 

我得到

错误C2440: '初始化':无法从 '无效(__cdecl *)(无效)' 到 'VGThreadFunction'

如何转换我使用vg_thread_create?

编辑

我尝试这样做:

void* doit(void* donothingvar) { 
    cout << "printing stuff in new thread\n"; 
    return donothingvar; 
} 

然后在功能:

VGThreadFunction testfunc = (VGThreadFunction)doit; 

int ret = vg_thread_create(testfunc, 0, 0, 0, 0, 0, 0); 

我然后调用vg_thread_create时收到访问冲突。

如果我踏入时,它调用_beginthreadex

Unhandled exception at 0x0040f5d3 in threadtest.exe: 0xC0000005: Access violation writing location 0x00000000. 

任何想法,它实际上崩溃的功能?

通过进入函数我解决了我不得不传入一个有效的指针 - 传递零导致空解除引用。对不起,有点具体。

回答

6

是的,函数签名必须匹配。只需在你的函数中添加一个虚拟参数。

+0

为什么要投它不工作? – 2012-10-17 18:19:33

+0

@ H2CO3,取决于编译器使用的参数传递约定,它可能会搞砸了。即使它有效,我也确信它是未定义的行为。 –

+0

标准报价请 – 2012-10-17 18:22:33