我想在python代碼中呼叫ac函式,并傳入一個python字典作為引數。
小c
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
PyObject *changeDict(PyObject *dict){
if(PyDict_Check(dict) == 1){
system("echo '==== is a dict ====' | systemd-cat -t 'little.c'");
}
// modify some value
return dict;
}
我使用這些命令來編譯 little.c:
gcc -g -fPIC -c little.c -I/usr/include/python2.7 -lpython2.7
gcc -shared little.o -o little.so
并移動到 LD_LIBRARY_PATH
mv little.so /usr/lib
小.py
from ctypes import *
mydll = PyDLL("little.so")
dic = {"status": 0}
dic = mydll.changeDict(dic)
print(dic)
python little.py
然后我得到了這個錯誤:
Traceback (most recent call last): File "little.py", line 13, in <module> dic = mydll.changeDict(dic) ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1
是否可以將 python 字典直接傳遞給 C 函式?
uj5u.com熱心網友回復:
始終為您的函式定義.argtypes和.restype以便ctypes可以對您的引數進行型別檢查并知道如何將它們編組到 C 和從 C 編組。 py_object是直接傳遞 Python 物件時使用的型別。
作業示例:
// test.c
#include <Python.h>
__declspec(dllexport) // for Windows exports
PyObject *changeDict(PyObject *dict) {
PyObject* value = PyUnicode_FromString("value");
PyDict_SetItemString(dict, "key", value); // Does not steal reference to value,
Py_DECREF(value); // so free this reference
Py_INCREF(dict); // because we're returning it...
return dict;
}
# test.py
from ctypes import *
# Use PyDLL when calling functions that use the Python API.
# It does not release the GIL during the call, which is required
# to use the Python API.
mydll = PyDLL('./test')
mydll.changeDict.argtypes = py_object, # Declare parameter type
mydll.changeDict.restype = py_object # and return value.
dic = {}
x = mydll.changeDict(dic)
print(x)
dic = {'key':2}
mydll.changeDict(dic) # Modified in-place, so really no need to return it.
print(dic)
輸出:
{'key': 'value'}
{'key': 'value'}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/358330.html
