我正在尝试使用 LD_PRELOAD 技术拦截 libpthred( POSIX ) 函数调用。首先,我尝试创建自己的共享库,其函数名称与 pthread 库中的相同。下面是我自己创建的pthread_create函数的一个例子,它首先获取pthread库中原pthread_create函数的地址,然后使用函数指针调用pthread库中的原函数。
#include <stdio.h>
#include <dlfcn.h>
#include <pthread.h>
int pthread_create (pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void*), void *arg )
{
int return_value;
static int (*fptr) () = 0;
printf( "\n this is the test of LD_PRELOAD" );
char *lError = dlerror();
if( fptr == 0 )
{
fptr = ( int (*) () ) dlsym( RTLD_NEXT, "pthread_create" );
if( fptr == 0 )
{
(void) printf( "Error dlopen: %s", dlerror() );
return 0;
}
}
return (return_value);
}
我试过这样编译:
g++ -fPIC -g -rdynamic -c -Wall ldtest.C -lrt -lpthread -ldl
但它给出了以下错误
ldtest.C:26: error: too many arguments to function
第26行就是程序中的这一行。
return_value = (*fptr)( thread, attr, start_routine, arg );
谁能告诉我这里有什么问题或者这是编译它的正确方法吗?
最佳答案
您发布的代码中没有这样的第 26 行。请发布相关代码。
如果您在第 26 行中使用的 fptr
与上面的 pthread_create
中的声明完全相同(即带有空参数列表 ()
),则代码将不会编译为 C++,因为在 C++ 中,作为参数列表的 ()
意味着“根本没有参数”。而您正试图传递参数,这就是导致错误的原因。如果您希望您的代码像 C++ 一样工作,请使用适当的参数列表声明 fptr
。
用 ()
作为参数列表的声明将在 C 代码中工作,因为在 C 中它意味着“未指定的参数”,但在 C++ 中则不行。
关于c++ - 我的程序有什么错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2157354/