cython - 在c程序中使用cython和ctypes接口调用python函数获取'c'之类的结构
问题描述
我是 cython/ctypes 的新手,我试图使用 cython 接口从 c 程序调用 python 函数,但数据为空或不正确。这是示例程序
蟒蛇函数
$ cat c_struct.py
#!/usr/bin/env python2.7
from ctypes import *
class Request(Structure):
_pack_ = 1
_fields_ = [
('type', c_ubyte),
('subtype', c_ubyte),
('action', c_ubyte),
('checksum', c_ushort)
]
def __repr__(self):
return "'type': {}, 'subtype': {}, 'action': {}, 'checksum': {}".format(self.type,
self.subtype, self.action, self.checksum)
req_msg = Request()
def get_message(typ):
if typ == 1:
req_msg.type = 12
req_msg.subtype = 2
req_msg.action = 3
req_msg.checksum = 0x1234
return req_msg
else:
return "String object From Python"
cython 包装
$ cat caller.pyx
import sys
sys.path.insert(0, '')
from c_struct import get_message
cdef public const void* get_data_frm_python(int typ):
data = get_message(typ)
print "Printing in Cython -",data
return <const void*>data
最后是我的“C”来电者
cat main.c
#include <Python.h>
#include "caller.h"
#include <stdio.h>
typedef struct {
uint8_t type;
uint8_t subtype;
uint8_t action;
uint16_t checksum;
} __attribute__ ((packed)) request_t;
int
main()
{
PyImport_AppendInittab("caller", initcaller);
Py_Initialize();
PyImport_ImportModule("caller");
const char* str = get_data_frm_python(2);
printf("Printing in C - %s\n", str);
const request_t* reqP = (request_t*)get_data_frm_python(1);
printf("Printing in C - %u, %u, %u, %u\n", reqP->type, reqP->subtype, reqP->action, reqP->checksum);
return 0;
}
和一个简单的makefile来构建它
$ cat Makefile
target = main
cy_interface = caller
CY := cython
PYTHONINC := $(shell python-config --includes)
CFLAGS := -Wall $(PYTHONINC) -fPIC -O0 -ggdb3
LDFLAGS := $(shell python-config --ldflags)
CC=gcc
all: $(target)
%.c: %.pyx
$(CY) $+
%.o: %.c
$(CC) -fPIC $(CFLAGS) -c $+
$(target): $(cy_interface).o $(target).o
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
最后是输出:(
$ ./main
Printing in Cython - String object From Python
Printing in C -
Printing in Cython - 'type': 12, 'subtype': 2, 'action': 3, 'checksum': 4660
Printing in C - 1, 0, 0, 0
有人可以帮助我了解我做错了什么吗?
注意:-如果我将 void* 更改为 char* 至少可以正确获取字符串数据,但是 struct 会出现段错误
$ cat caller.pyx
import sys
sys.path.insert(0, '')
from c_struct import get_message
cdef public const void* get_data_frm_python(int typ):
data = get_message(typ)
print "Printing in Cython -",data
return <const char*>data
$ ./main
Printing in Cython - String object From Python
Printing in C - String object From Python
Printing in Cython - 'type': 12, 'subtype': 2, 'action': 3, 'checksum': 4660
TypeError: expected string or Unicode object, Request found
Exception TypeError: 'expected string or Unicode object, Request found' in 'caller.get_data_frm_python' ignored
Segmentation fault
解决方案
<const void*>data
data
是一个 Python 对象 (a PyObject*
)。这条线将其转换PyObject*
为无效。PyObject*
将 a 解释为字符串或 a绝对是不合理的request*
。
<const char*>data
这将获得一个指向 Python 字符串的第一个元素的指针(您的结构不是)。指针仅在data
还活着时才有效。不幸的是,数据是一个函数局部变量,因此几乎可以立即释放。很难确切地说出这里发生了什么,但这绝对是错误的。
我真的不明白你想在这里实现什么,所以我很难就如何做得更好提供建议。也许放弃 ctypes 并将 Cython 与 C 联合使用?
推荐阅读
- terraform - 将变量列表放入 Terraform 中的内联策略
- ubuntu - SSL 握手时的 nginx 严重错误(例程:ssl3_get_client_hello:length 太短),同时 SSL 握手)
- debian - 根据官网安装rokcketmq 4.3.2 for debian,但无法“启动名称服务器”
- visual-studio-code - (为什么)我会在项目中同时使用 .editorconfig 文件和 VS 代码工作区设置吗?
- excel - 在单元格中输入值,而不是从剪贴板粘贴
- c# - 添加包含帧的 Duration
- python - 在浏览器控制台中出现错误 - 未捕获的 ReferenceError: allauth 未定义
- windows - 如何在 PC 上打开 Linux .bin 文件?
- c++ - 将拆分的字符串分配为子字符串
- java - 删除链接对象?