[英]python pass to C-API structure with a pointer to another structure as an element
[英]How do you correctly pass a pointer between calls with Python C-API
我正在編寫一個 python + c 模塊,我正在嘗試傳遞一個指向我需要的某個結構的指針。 我正在使用 PyCapsule 來封裝指針,但是在從中檢索指針時遇到了問題。 使用的 C 函數如下:
static PyObject *
spam_new (PyObject *self, PyObject *args)
{
unsigned int number;
struct spam *pointer;
if (!PyArg_ParseTuple(args, "I", &number)) {
return NULL;
}
state = (struct spam*) malloc(sizeof (struct spam));
if (state == NULL) {
return NULL;
}
spam_init(*pointer, number);
return PyCapsule_New((void*) pointer, "spam", &spam_destroy);
}
static PyObject *
spam_get (PyObject *self, PyObject *args)
{
PyObject *capsule, *result;
void *raw_pointer;
struct spam *pointer;
unsigned long long int number;
if (!PyArg_ParseTuple(args, "OK", capsule, &number)) {
return NULL;
}
printf("[DEBUG] Number: %llu\n", number);
printf("[DEBUG] Capsule pointer: %p\n", capsule);
raw_pointer = PyCapsule_GetPointer(capsule, "spam");
if (raw_pointer == NULL) {
return NULL;
}
pointer = (struct spam*) raw_pointer;
.
.
.
}
它們都用 METH_VARARGS 聲明。 在 python 中, custom.new(1) 按預期返回一個膠囊,我將其存儲在變量c 中。 調用 custom.get(c, 14) 時,python 在 PyCapsule_GetPointer 函數調用處崩潰。 兩個打印都顯示相同的 (14),這意味着 PyArg_ParseTuple 沒有將膠囊作為參數傳遞。
出於安全原因,不能將指針作為long傳遞。
謝謝。
在Python 文檔中聲明“O”格式字符串將嘗試獲取指向 PyObject(一個 PyObject*)的指針,而不是 PyObject。
因此,當使用PyArg_ParseTuple
獲取 PyObject* 時,您必須傳遞一個指向 PyObject* 的指針。
通過在行中的膠囊中添加 & 來修復提供的代碼
if (!PyArg_ParseTuple(args, "OK", &capsule, &number)) {
感謝Davis Herring的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.