c++ - 使用 ctypes 向 C/C++ 库提供函数的外部定义

标签 c++ python c ctypes

我有一个使用函数的简单库 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/

相关文章:

c++ - 正确使用工厂类的标准 move

python - 是否可以使用单个记录器编写许多不同的日志文件?

c - Typedef 结构查找程序不断崩溃

java - 枚举具有 N 个元素的一维数组的所有 k 分区?

c - 如何使用二元运算高效地执行 ==?

c++ - 如何仅为函数指针编写正确的构造函数?

c++ - C与C++,void **指针的处理

c++ - 如何以编程方式选择 QTableView 中的下一行

Windows 上的 Python GTK CSS 问题

python - 如何顺序聚合dask Bag的内容?