如何从具有ctypes的C ++函数返回对象? [英] how do I return objects from a C++ function with ctypes?
问题描述
我有两个C ++类,即Container和Item,它们看起来像:
I have two C++ classes, Container and Item, that look like:
class Item{
public:
Item(std::string* name,int id);
std::string* getName();
private:
std::string* name;
int id;
};
class Container {
public:
Container();
Item* getItem(int id);
private:
std::vector<Item*> items;
};
我想在Python中创建和使用Container,所以我写了一个C接口来编译共享库:
I want to create and use Container in Python, so I wrote a C interface to compile a shared library:
extern "C" {
Container* Container_init(){return new Container();}
Item* Container_getItem(Container* container,int id){return container->getItem(id);}
std::string* Item_getName(Item* item){return item->getName();}
}
和一个Python包装器:
and a Python wrapper:
from ctypes import *
lib = cdll.LoadLibrary(myLibPath)
class Item(object):
def getName(self):
return lib.Item_getName(self.obj)
class Container(object):
def __init__(self):
self.obj = lib.Container_init()
def getItem(self,id):
return lib.Container_getItem(self.obj,id)
lib.Container_getItem.restype = Item
lib.Container_getItem.argtypes = [c_void_p,c_int]
c = Container()
print c.getItem(5).getName()
何时输入此代码运行,它在行上引发TypeError object()不带参数
When this code runs, it raises a TypeError "object() takes no parameters" at line
return lib.Container_getItem(self.obj,id)
我在文档,但是我显然丢失了一些东西,如何制作 Container.getItem
用Python返回项目吗?
I read about restype and argtype in the documentation but I'm obviously missing something, how can I make Container.getItem
return an Item in Python?
推荐答案
替换 Item_getName
如下所示,返回 char *
而不是 string *
:
Replace Item_getName
as follow to return char *
instead of string *
:
const char* Item_getName(Item* item) { return item->getName()->c_str(); }
Item
类丢失 __ init __
。进行如下更改(这是 TypeError
的原因):
Item
class is missing __init__
. Change as follow (This is the cause of the TypeError
):
class Item(object):
def __init__(self, obj):
self.obj = obj
def getName(self):
return lib.Item_getName(self.obj)
并将以下内容添加到Python脚本中(在调用 getName $ c $之前c>方法)正确获取名称:
And add following to Python script (before call getName
method) to correctly get name:
lib.Item_getName.restype = c_char_p
lib.Item_getName.argtypes = ()
然后,您会得到想要的东西。
Then, you will get what you want.
这篇关于如何从具有ctypes的C ++函数返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!