修改函数指针的签名
我在这里遇到一个小问题,我有这个函数指针:
typedef void* (* funcPointer)(const void *in, int ilen, void *out, int *olen)
并且这个函数
void* foo1(const void *in, int ilen, void *out, int *olen)
{
if(CONST_VALUE_1 > iLen)
//do something
else
//do something else
return whatever;
}
在代码中的某处
// ...
funcPointer fpointer = foo1;
if(someArgument > SOME_OTHER_CONSTANT)
// where foo2 is the same as foo1 except that it uses CONST_VALUE_2
fpointer = foo2;
bar( someVariable, anotherVariable, fpointer);
// ...
正如你所看到的,在这个函数的主体中有一个CONST_VALUE_X
。我希望能够删除常量并使用第五个参数。由于我无法修改签名,我想知道是否需要执行某些操作或使用每个可能的常量值复制粘贴该函数...
谢谢
I'm running in a little issue here, I've got this function pointer :
typedef void* (* funcPointer)(const void *in, int ilen, void *out, int *olen)
And this function
void* foo1(const void *in, int ilen, void *out, int *olen)
{
if(CONST_VALUE_1 > iLen)
//do something
else
//do something else
return whatever;
}
Somewhere in the code
// ...
funcPointer fpointer = foo1;
if(someArgument > SOME_OTHER_CONSTANT)
// where foo2 is the same as foo1 except that it uses CONST_VALUE_2
fpointer = foo2;
bar( someVariable, anotherVariable, fpointer);
// ...
As you can see, there is a CONST_VALUE_X
in the body of this function. I would like to be able to remove the constant and use a fifth argument instead. Since I can't modify the signature, I was wondering if there was something to do or copy-paste the function with every possible constant value...
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您无法修改函数签名,那么正如您所说,您将不会有第五个参数!
我看到三个选项:
我猜你可以将它硬塞到其他
void *
参数之一中(例如定义一个包含in
的原始值的结构,并且“常量”值,然后将其作为in
传递)。在调用函数之前设置全局变量。 这是一个坏主意。
您可以将此函数编写为宏,以避免复制粘贴维护噩梦。 这是一个坏主意。
If you can't modify the function signature, then as you say, you won't have a fifth argument!
I see three options:
I guess you could shoehorn it into one of the other
void *
arguments (e.g. define a struct that contains the original value forin
, and the "constant" value, and then pass this in asin
).Set a global variable before calling the function. This is a bad idea.
You could write this function as a macro, to avoid the copy-and-paste maintenance nightmare. This is a bad idea.
您可以将常量替换为调用者可以临时更改的内容(例如全局变量)。
例如:
并且,在函数中:
You could replace the constant with something that the caller can temporarily change (like a global variable).
For example:
And, in the function:
你想要的东西叫做闭包,而C并没有对闭包的显式支持。您可以通过修改 API 以携带函数指针和参数指针而不仅仅是函数指针来实现相同的目的。然后,您只需要该函数的版本:一个使用显式调用者提供的参数,另一个使用来自携带的参数指针的值。
What you want is called a closure, and C does not have explicit support for closures. You can achieve the same thing by modifying your API to carry around a function pointer and argument pointer instead of just a function pointer. Then you just need to versions of the function: one that uses the explicit caller-provided argument, and another that uses a value from the carried argument pointer.