0

This is similar to the question in Function pointer with undetermined paramater but when I tried it ,I get a compile errors:

error: too many arguments to function 'accessVariant'

error: void value not ignored as it ought to be

I define this at the top of my C file:

typedef void (*callBackHandler)(void*);
callBackHandler accessVariant= NULL;

I have a call back registration function:

void registerCallbackHandler(callBackHandler ptr_reg_callback)
{
    if (ptr_reg_callback == NULL)
    {
        return;
    }
    else
    {
        accessVariant = ptr_reg_callback;
    }
}

Inside the code I check for some boolean ,and then I register a specific type of access function:

if (bool)
{
    registerCallbackHandler((callBackHandler)aRead16);
}
else
{
    registerCallbackHandler((callBackHandler)aRead32);
}

Each of aRead16 and aRead32 takes different kinds of arguments.

Then I make the call: (*accessVariant)( (void*)arg1,(void*) arg2, (void*)&value )

4

1 回答 1

0

不要试图将方形钉子强行插入圆孔,只需使用圆形钉子。声明callBackHandler

typedef void (*callbackHandler)(void *, void *, void *);

您的函数没有不确定数量的参数。它们具有三个参数。

void*请注意,由于明确的演员阵容,您仍然如履薄冰。删除它们并相应地修复您的原型。

补充:如果函数并非都具有完全相同的参数列表(例如您的示例,其中第三个参数有时是 auint16*有时是 a uint32*),那么您需要多个 typedef 并适当地选择一个。

typedef void (*genericCallback)(void);
typedef void (*callbackUint32Uint16Pint16Ptr)(uint32, uint16, uint16 *);
typedef void (*callbackUint32Uint16Uint32Ptr)(uint32, uint16, uint32 *);

void aRead16(uint32, uint16, uint16 *);
void aRead32(uint32, uint16, uint32 *);

void registerCallbackHandler(genericCallback callback)
{
    if (callback == NULL)
    {
        return;
    }
    else
    {
        accessVariant = callback;
    }
}

void RegisterSomething()
{
    if (use_the_uint16_callback)
    {
        registerCallbackHandler((genericCallback)aRead16);
    }
    else
    {
        registerCallbackHandler((genericCallback)aRead32);
    }
}

void CallTheCallback()
{
    if (use_the_uint16_callback)
    {
        ((callbackVoidPtrVoidPtrUint16)accessVariant)(x, y, z16);
    }
    else
    {
        ((callbackVoidPtrVoidPtrUint32)accessVariant)(x, y, z32);
    }
}

这要求use_the_uint16_callback保持不变,accessVariant因为您必须在使用之前将函数指针转换回其原始类型。

更新以更改所有参数。以前的版本是基于评论中提供的不正确信息。(前两个参数最初声称是指针,但在评论中显示它们不是。第三个参数最初声称是 a uint16,但在评论中显示它实际上是uint16 *。)

于 2013-11-14T20:46:16.957 回答