0

libffi 的手册页提供了一个示例,该示例本质上需要一个指向函数的指针(在示例中为puts)。

但是,如果我只知道函数的名称,但实际上没有指针(如果 ffi 用于动态编程语言中通常会发生这种情况),我该怎么办?

说,我想做这样的事情(伪代码):

cif = null
s = "Hello World"
args = []
values = []
args[0] = ffi.type_pointer
values[0] = address_of(s)
if(ffi.prepare(cif, ffi.DEFAULT_ABI, ffi.type_uint, args)):
     ffi.call(cif, "puts", values)

简而言之,我想让 libffi 动态查找类似于 dlfcn/LoadLibrary 的函数(如果首先由 ffi 支持),然后使用提供的 FFI CIF 类型调用它。

libffi可以做到这一点吗?一个简单的例子会是什么样子?

4

1 回答 1

0

有两种可能性 - 一种需要程序员的预谋。

根据 o/s,有一些与共享库相关的设施,用于从程序或其共享库中查找符号。

在许多 Unix 系统和特别是 Linux 上,这些设施是在<dlfcn.h>and are dlopen()and dlsym()(anddlclose()等) 中声明的。给定共享库的适当句柄,您可以使用:

int (*ffi_ptr)(const char *) = dlsym(ffi_handle, "ffi_function_name");

您必须考虑强制转换 - 通常是残酷的 - 以避免编译警告。

另一种有预谋的技术是建立一个函数名称和函数指针表,您可以在其中搜索名称并使用相应的指针:

struct ptr_function
{
    void (*func_ptr)(void);
    const char *func_name;
};

static const struct ptr_function[] =
{
    { func_1, "func_1"       },
    { func_2, "func_2"       },
    { func_2, "func_synonym" },
};

enum { NUM_PTR_FUNCTION = sizeof(ptr_function) / sizeof(*ptr_function) } ;

Note that this technique allows for synonyms in a way that the dlsym() mechanism does not. However, the premeditation is often a major stumbling block. It is a technique that harks back to the 80s and early 90s when shared libraries were not universally available. Once again, the need for casts can make the code somewhat more complex.

于 2012-01-15T05:39:05.703 回答