我有一个使用函数的简单库 hello_printf(const char *format, ...) 在其 API 之一中。使用时 C 中的这个库,我将 hello_printf 的函数指针指向 使用库和代码的外部应用程序中的 printf 可以无缝运行。
hello_printf 不是 API,但用于实现一个 API的。这样做的原因是我想要外部应用程序 使用库提供 printf(外部绑定(bind))的实现。
现在我想在 python 中使用这个库,我正在使用 ctypes 调用 API,但我无法找到一种方法来找到函数与 ctypes 的提供外部绑定(bind)。 即,将 hello_printf() 指向 libc 的 printf,使得“hello_printf = libc.printf”。
最佳答案
您正在寻找 ctypes 数据类型的 in_dll
方法。
C:
#include <stdlib.h>
int (*hello_printf)(const char *format, ...) = NULL;
int test(const char *str, int n) {
if (hello_printf == NULL)
return -1;
hello_printf(str, n);
return 0;
}
类型:
from ctypes import *
cglobals = CDLL(None)
lib = CDLL("./lib.so")
hello_printf = c_void_p.in_dll(lib, "hello_printf")
hello_printf.value = cast(cglobals.printf, c_void_p).value
>>> lib.test("spam %d\n", 1)
spam 1
0
关于c++ - 使用 ctypes 向 C/C++ 库提供函数的外部定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20550701/