我在 Python 中有一個物件,例如:
import test
class Test:
def __init__(self, n):
self.n = n
t = Test(4)
test.c_function(t)
我想在 c 中閱讀它
static PyObject* py_c_function(PyObject* self, PyObject* args) {
PyObject obj;
if (!PyArg_ParseTuple(args, "O", &obj))
return NULL;
int n;
// I want to access the the n member of the object or create a new Test struct
return Py_BuildValue("i", n);
// or
return Py_BuildValue("i", test.n);
}
如何訪問 pyObject 中的成員以獲取自定義 python 資料結構?
我該如何做相反的事情,將值分配給稍后將在 python 中呼叫的物件?
編輯:
正如 kpie 所建議的,根據檔案使用函式 PyObject_GetAttrString 這應該等效于 obj.n。
PyObject * o = PyObject_GetAttrString(&obj, "n");
long n;
n = PyLong_AsLong(o);
但是當我運行它時,我得到了錯誤:
SystemError: ../Objects/dictobject.c:1438: bad argument to internal function
編輯 2
我正在使用 GCC 編譯 c 代碼:
gcc -I/usr/include/python3.8/ -shared -o test.so -fPIC test.c
然后在我添加的python腳本中
import test
uj5u.com熱心網友回復:
該函式PyObject_GetAttrString(obj,"attr")可以讀取類似于 kpie 注釋的 obj.attr 的 python 類的屬性。
問題是PyObject obj;那不是一個指標。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/436491.html
上一篇:從檔案中讀取資料并決議
