1

I know the reasons why this is a bad idea and I also know that this is the reason C++ templates were created, but I'm doing it in C for the fun and learning.

I'm embedding Python into my application and I wanted to make it possible to register certain C functions, with any arbitrary type, to be callable at the application run-time. Because of this a pointer to them is stored (as a simple void*).

With some basic macro fun I have gotten all the information I need about these functions and stored that too - the function pointer, the size of the return value (and if it is void), the number of arguments and each of their sizes.

So I'm stuck at the final stage - which is the actual calling of the function pointer with the appropriate data. I'm fairly certain this sort of thing should be possible (I've caused stack errors in my own time), but I was wondering if there was a more...legitimate way to do it.

I guess the ideal would look something like this:

void call_function(void* function, void* return, void* arg_data, int arg_data_size);

Does such a thing exists?

Thanks

4

1 回答 1

1

您可以声明一个指向函数的函数指针void* (*f) (void*);,该函数接受一个void*参数并返回一个void*返回值——您可以将它放在call_function.

然后调用call_function为:

void* function(void*);
ret_type ret;
arg_type arg_data;
call_function(&function, (void*)&ret, (void*)&arg_data, sizeof(arg_data));

wherearg_type是您要在内部使用的实际参数类型,function并且ret_type是 的返回值的实际类型function

注意:您可能还想指定返回值类型的大小。

注意:这将适用于一个参数的任何函数。该解决方案可以扩展到 中的固定/已知数量的参数function,但不能处理未知数量的参数。

注意:return不允许将第二个参数命名为return关键字。

于 2012-04-09T20:30:45.670 回答