我需要将一个字符串指针从C传递到Python,这样Python就可以更新指针,C也可以稍后读取它。
步骤
- C设置一个
char**
- C调用Python
- Python分配内存
- Python更新
char**
- C读取字符串
C代码:
#include <stdio.h>
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
typedef void (*CALLBACK)(char**);
CALLBACK g_cb;
// Expose API to register the callback
API void set_callback(CALLBACK cb) {
g_cb = cb;
}
// Expose API to call the Python callback with a char**
API void call_python_function(char** pp) {
if(g_cb) {
g_cb(pp);
printf("Python response: %s\n", *pp);
}
}
Python代码:
import ctypes as ct
CALLBACK = ct.CFUNCTYPE(None, PPCHAR)
dll = ct.CDLL('./test')
dll.set_callback.argtypes = CALLBACK,
dll.set_callback.restype = None
dll.call_python_function.argtypes = POINTER(POINTER(ctypes.c_char)),
dll.call_python_function.restype = None
dll.set_callback(my_function)
def my_function(pp):
buffer = ct.create_string_buffer(128)
pp = buffer
输出:
Python response: (null)
编译时没有错误或警告,C可以调用Python函数,没有问题,但Python不能更新char**
。我的问题是如何将字符串指针从C传递到Python?
1条答案
按热度按时间djp7away1#
下面是一个将
char**
从C传递到Python的工作示例。测试.c
测试.py
输出量: