Python的ctypes的:包木窗C ++类与运营商 [英] Python ctypes: wraping c++ class with operators
问题描述
我想换一个小的测试C ++类使用ctypes的Python中使用。该类称为边缘
并有一个朋友比较(==)操作符。我有实施包装蟒蛇code中的比较功能的困难。
I want to wrap a small test C++ class for use in python using ctypes. The class is called Edge
and has a friend comparison (==) operator. I am having difficulty implementing the comparison feature in the wrapper python code.
一个简洁的边缘
标题是:
class Edge {
private:
int p1, p2;
public:
Edge(const int pp1, const int pp2);
~Edge(){};
friend bool operator==(const Edge &e1, const Edge &e2);
};
我写的Python包装是:
The python wrapper I have written is:
from ctypes import *
lib = cdll.LoadLibrary('./libedge.so')
lib.Edge_new.argtypes = [c_int, c_int]
lib.Edge_new.restype = c_void_p
lib.compare_edge.argtypes = [c_void_p, c_void_p]
lib.compare_edge.restype = c_bool
class Edge(object):
def __init__(self, pp1, pp2):
self.obj = lib.Edge_new(c_int(pp1), c_int(pp2))
def __eq__(self, other):
return lib.compare_edge(self.obj, c_void_p(other))
其中,Edge_new和compare_edge是被定义为C ++程序:
Where, Edge_new and compare_edge are C++ routines that are defined as:
#include "Edge.hpp"
extern "C" {
Edge* Edge_new(const Int32 pp1, const Int32 pp2) { return new Edge(pp1, pp2); }
bool compare_edge(Edge *e1, Edge *e2) {
return *e1 == *e2;
}
}
构造函数工作正常。当我比较两个边缘对象 E1 == E2
我得到以下类型错误:
Traceback (most recent call last): File "Edge.py", line 21, in <module>
print e1 == e2 File "Edge.py", line 16, in __eq__
return lib.compare_edge(self.obj, c_void_p(other)) TypeError: cannot be converted to pointer
我不明白什么是错误手段,最有可能的,为什么事情错了,但我不知道如何解决它。我编译C ++ code使用gcc 4.7和蟒蛇间preTER是64位。
I do understand what the error means, and most likely why something is going wrong, but I don't know how to fix it. I am compiling C++ code with gcc 4.7 and the python interpreter is 64 bit.
推荐答案
但问题是,你要投一个Python对象为无效*
,而不是无效*
您已经连接到该对象的 OBJ
属性。
Problem is, you're trying to cast a Python object to a void *
, rather than the void *
you already attached to that object's obj
attribute.
这应该是为改变简单...
It should be as simple as changing...
def __eq__(self, other):
return lib.compare_edge(self.obj, c_void_p(other))
...到...
...to...
def __eq__(self, other):
return lib.compare_edge(self.obj, other.obj)
到 c_void_p
的显式调用应该是不必要的,因为你已经宣布该行的类型...
The explicit call to c_void_p
should be unnecessary, since you already declared the types in the line...
lib.compare_edge.argtypes = [c_void_p, c_void_p]
这篇关于Python的ctypes的:包木窗C ++类与运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!