我的问题是如何通过 ctypes 将 C 函数的制表符分隔输出解析为 pandas DataFrame:
我正在使用 ctypes 围绕 C 库在 Python3.x 中编写 Python 包装器。 C 库当前执行数据库查询。我正在访问的 C 函数 return_query()
从查询中返回以制表符分隔的行,给定文件路径、索引和查询字符串:
int return_query(structname **output, const char *input_file,
const char *index, const char *query_string);
如您所见,我使用 output
作为存储查询中所有记录的位置,其中 structname
是行的结构
我还有一个打印到 STDOUT 的函数:
int print_query(const char *input_file,
const char *index, const char *query_string);
我的目标是通过 ctypes 访问这些函数,并将制表符分隔的行输出传递到 pandas DataFrame。
我的问题是:
(1) 我可以尝试解析 print_query()
的 STDOUT;但是,这些查询可能会导致大型制表符分隔的 DataFrame。我担心这个解决方案效率不高,因为它可能无法扩展到 +10000 行。其他问题大致涵盖了如何通过 ctypes 在 Python 中从 C 函数中捕获 STDOUT:
Capturing print output from shared library called from python with ctypes module
(2) 我能否以某种方式访问 output
,并将其传递给 pandas DataFrame?我目前不确定这将如何工作,例如
import ctypes
lib = CDLL("../libshared.so") ### reference to shared library, *.so
lib.return_query.restype = ctypes.c_char
lib.return_query.argtypes = (???, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p)
第一个参数应该是什么,我如何将它传递给可能是 pandas DataFrame 的东西?
(3) 也许最好将返回制表符分隔行的 C 函数重写为更易于通过 ctypes 访问的内容?
最佳答案
我正要发表评论,但 stackoverflow 阻止了我发表评论。
1- pandas 对象传递给像 PyObject * 这样的 c 函数,所以 lib.return_query.argtypes = (c_types.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p)
2- 如果您要返回制表符分隔的行,听起来更像 ctypes.c_char_p,而不是 lib.return_query.restype = ctypes.c_char。而你的函数 int return_query,应该是 char * return_query
这些是评论和观察,不是完整的答案....
关于Python ctypes : how to pass row outputs from a C function into a pandas DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50777214/