1

我想在 WaitAndCallFunc() 函数中调用 Test1() 方法。

代码:

typedef void (*func)();

void StartTimer(void* pFuncAddr);
void WaitAndCallFunc(void* pPtr);

void WaitAndCallFunc(void* pPtr)
{
    int i = 0;
    int nWaitTime = 3;

    while(1)
    {
        Sleep(1000);
    //  I want pPtr to call Test1 Function;
        if(i == nWaitTime)
            break;
    }

    _endthread();
}
void StartTimer(void* pFuncAddr)
{
    _beginthread(WaitAndCallFunc, 0, pFuncAddr);
}
void Test1();
int main(int argc, char* argv[])
{

    StartTimer(Test1);

    Sleep(5000);

    return 0;
}

void Test1()
{
    cout << "Testing Thread\n";
}
4

4 回答 4

5

我不确定我是否理解你的问题,但试试这个:

((func)pPtr)();
于 2009-07-08T12:28:11.240 回答
3

投射和调用:

typedef void (*func)();

void WaitAndCallFunc(void* pPtr)
{
    int i = 0;
    int nWaitTime = 3;

    while(1)
    {
        Sleep(1000);

        func f=(func)pPtr;   // cast to correct pointer to function type
        f();                 // and call!

        if(i == nWaitTime)
                break;
    }

    _endthread();
}
于 2009-07-08T12:26:20.053 回答
3

严格来说,在 C 语言中,您不应该在函数指针和其他类型的指针之间进行转换。不能保证按您的预期工作。

所以一个更迂腐的正确版本看起来像:

struct hook {
    void (*func)();
};

void StartTimer(void* pFuncAddr);
void WaitAndCallFunc(void* pPtr);

void WaitAndCallFunc(void* pPtr)
{
    struct hook *hook_ptr = pPtr;

    hook_ptr->func();

    _endthread();
}

void StartTimer(void* pFuncAddr)
{
    _beginthread(WaitAndCallFunc, 0, pFuncAddr);
}

void Test1();

int main(int argc, char* argv[])
{
    struct hook hook_test1 = { &Test1 };

    StartTimer(&hook_test1);

    Sleep(5000);

    return 0;
}

请注意,这里是与 void * 相互转换的结构指针,而不是函数指针本身。这还有一个好处是,如果您需要将更多值传递给 Test1(),您可以将更多值填充到结构中。

于 2009-07-08T13:41:11.263 回答
2

实际上,将函数指针转换为 void* 或将 void* 转换为函数指针在当前的 C 或 C++ 中是不允许的——即使大多数编译器都会编译它

有两种方法可以在不编译直接转换的编译器上来回转换(使用 C 语法):

方法一(先转为积分中介)

((func) (intptr_t) pPtr)();  // call the void*

StartTimer( (void*) (intptr_t) &Test1); // pass function pointer to void*

方法2(使用void**)

func f = 0;
*((void**)&f) = pPtr;
f();  

StartTimer( *((void**) &Test1)); // pass function pointer to void*

您可以参考以下线程以获得更多解释:Function pointers casting in C++

于 2009-07-08T13:43:28.500 回答