您好我正在开发一个类似的程序:
./Filters File [filters...]
过滤器可以是很多.so库,我想自己创建并将它们附加到文件中。但是所有库都具有相同的功能process(a1,a2,a3)
,只是每个库都做了不同的事情。
我试图像这样使用它:
/*Open the library*/
if (!(descriptor_lib=dlopen(dir_filter, RTLD_LAZY))) {
fprintf(stderr, MYNAME": %s\n", dlerror());
return(1);
}
/*We find the function we want to use*/
if (!(fn=dlsym(descriptor_bib, "process"))) {
fprintf(stderr, MYNAME": %s\n", dlerror());
return(1);
}
/*And then I try to use the function*/
printf("Number of chars readed: %d", fn(a1, a2, a3));
但是当我尝试编译时遇到此错误:error: too many arguments to function ‘fn’
dir_filter
是库的方向,但它是一个变量,因为我创建一个循环来读取所有过滤器,在dir_filter中复制实际的过滤器,然后使用上面的代码。
我认为如果我使用库的名称指定dir_filter
,它将起作用,但我不能这样做因为我需要让它适用于不同的过滤器(不同的库),它不会总是一样的。现在我只有3个库,但如果将来我想扩展它,我不想在每次添加新库时扩展代码。
那么我做错了什么,或者使用变量与dlopen合作是不可能的?
编辑:功能过程是这样的:
int process(char*buff_in, char*buff_out, int tam)
EDIT2:使用typedef
我可以修复函数指针,这就是问题所在。感谢您的回复,对不起我的英语。
答案 0 :(得分:1)
Assuming that your process
function is declared (in your plugin code) as
int process(int, int, int);
Then, you'll better define a typedef
for its signature (within the main program doing the dlsym
):
typedef int process_sig_t (int, int, int);
And you'll use that to declare the function pointer (there are some "direct" ways to declare in C a function pointer without using a typedef
for its signature, but I find them less readable).
process_sig_t *fnptr = NULL;
The compiler would then know the signature of the function referenced by that pointer.
(the initialization of fnptr
to NULL
could be omitted; it makes the code more readable and less error prone, since with a more reproducible behavior)
which you would fill using dlsym
e.g.
if (!(fnptr=dlsym(descriptor_bib, "process"))) {
fprintf(stderr, MYNAME": %s\n", dlerror());
return(1);
}
The use it
printf("Number of chars read: %d\n", (*fnptr) (a1, a2, a3));
BTW, function pointers could be called directly:
// less readable code, we don't know that fnptr is a function pointer
printf("Number of chars read: %d\n", fnptr (a1, a2, a3));
(it is better to end most printf
format strings with \n
; otherwise call fflush(3) since stdout
is often line-buffered)
BTW, your question is mostly about understanding function pointers (it would be relevant if the function pointer was obtained thru something else than dlsym
, e.g. using some JIT compiling library like GCCJIT).