2015-12-24 16 views
5

Tôi đang viết một phần mở rộng Python C. Tôi đang chuyển một từ điển Python đến hàm C. Tôi có thể phân tích cú pháp bằng cách sử dụng đoạn mã sau:CPython - Đọc Từ điển Python (các khóa/giá trị) bên trong một hàm C Được chuyển làm đối số

PyObject *large_dict = NULL; 
if (! PyArg_ParseTuple(args, "O!", &PyDict_Type, &large_dict)) return NULL; 
if (large_dict != NULL) 
{ 
    printf("Large Dictionary Not Null\n"); 
} 

Tại đây câu lệnh "Large Dictionary Not Null" được in, nghĩa là từ điển được phân tích thành công. Bây giờ tôi muốn truy cập các giá trị từ điển bằng cách chỉ định các phím, như trong python, chúng tôi thực hiện. tức là dict ['k1'] và giá trị này cho giá trị v1.

Tôi làm cách nào để truy cập các khóa/giá trị từ điển bên trong hàm C này?

Vui lòng đề xuất cho tôi giải pháp?

Trả lời

5

Bạn nên đi qua các liên kết, https://docs.python.org/2/c-api/dict.html Trích đưa ra dưới đây,

PyObject* PyDict_GetItem(PyObject *p, PyObject *key) 
Return value: Borrowed reference. 
Return the object from dictionary p which has a key key. Return NULL if the key key is not present, but without setting an exception. 

PyObject* PyDict_GetItemString(PyObject *p, const char *key) 
Return value: Borrowed reference. 
This is the same as PyDict_GetItem(), but key is specified as a char*, rather than a PyObject*. 

PyObject* PyDict_Items(PyObject *p) 
Return value: New reference. 
Return a PyListObject containing all the items from the dictionary, as in the dictionary method dict.items(). 

PyObject* PyDict_Keys(PyObject *p) 
Return value: New reference. 
Return a PyListObject containing all the keys from the dictionary, as in the dictionary method dict.keys(). 

PyObject* PyDict_Values(PyObject *p) 
Return value: New reference. 
Return a PyListObject containing all the values from the dictionary p, as in the dictionary method dict.values(). 

Giữ một mắt trên borrowed reference/new reference. Đó là chút khó khăn trong khi mã hóa cho các phần mở rộng Python.

+0

Giống như [this] (https://github.com/aerospike/aerospike-client-python/blob/master/src/main/conversions.c#L155) –

Các vấn đề liên quan