gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:22:28 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com