[英]Passing python objects as arguments to C/C++ function using ctypes
我有一個帶有將PyObject作為參數的函數的dll,例如
void MyFunction(PyObject* obj)
{
PyObject *func, *res, *test;
//function getAddress of python object
func = PyObject_GetAttrString(obj, "getAddress");
res = PyObject_CallFunction(func, NULL);
cout << "Address: " << PyString_AsString( PyObject_Str(res) ) << endl;
}
我想使用ctypes從python的dll中調用此函數
我的python代碼看起來像
import ctypes as c
path = "h:\libTest"
libTest = c.cdll.LoadLibrary( path )
class MyClass:
@classmethod
def getAddress(cls):
return "Some Address"
prototype = c.CFUNCTYPE(
c.c_char_p,
c.py_object
)
func = prototype(('MyFunction', libTest))
pyobj = c.py_object(MyClass)
func( c.byref(pyobj) )
當我運行此代碼時,我的Python代碼中存在一些問題
WindowsError:異常:讀取0x00000020的訪問沖突
任何改進python代碼的建議都會被采納。
我對您的代碼進行了以下更改,並且對我有用,但是我不確定這是100%正確的方法:
例如:
prototype = c.PYFUNCTYPE(
c.c_char_p,
c.py_object
)
func = prototype(('MyFunction', libTest))
func( MyClass )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.