Friday 15 June 2012

Python ctypes: wraping c++ class with operators -


I want to wrap a small test C ++ class for use in Python using ctypes. The class is called edge and is a friend comparison operator (==). I'm having difficulty implementing the comparative feature in the wrapper python code.

A short edge header:

  class edge {Private: Int p1, p2; Public: Edge (CRQP1, Constant PP2); ~ Edge () {}; Friend bool operator == (constant age and a1, constant age and a2); };   

Python wrapper I wrote:

  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 square Edge (object): def __init __ (self, Ppl, Pp2): self Kobj = LibkEdge_new (C_int (Ppl), C_int (Pp2)) def __eq __ (self, other): return lib.compare_edge (self.obj, c_void_p (other))   

are where the Edge_new and are defined as that compare_edge C ++ routines are:

  #include "Edge.hpp" extern "C" {Edge * Edge_new (constants Int32 pp1, constant Int32 pp2) {New Retention Edge ( Pp1, pp2); } Bool Comparison_Age (Age * E1, Age * E2) {return * E1 == * E2; }}   

The manufacturer works fine when I compare the two edge objects E1 == e2 I get the following writing error:

 < Code> Traceback (last most recent call): File "Edge.py", line 21, & lt; Module & gt; Print E1 == e2 file "Edge.py", line 16, __eq__ return lib.compare_edge (self.obj, c_void_p (other)) Writing Error:   

I did not change the pointer Understand what error means, and most likely why something is going wrong, but I do not know how to fix it. I am compiling C ++ code with GCC 4.7 and Python interpreter is 64 bit.

The problem is, you have a void * , the Code instead of zero * connected to the obj attribute.

change it should be as simple ...

  def __eq __ (self, other): returns lib.compare_edge (self.obj, c_void_p (Other) )   

... from ...

  def __eq __ (self, others): return lib.compare_edge (Self.obj, other.obj)   

Clear code c_void_p must be unnecessary, because you have already declared the type of lines in the line ...

  lib.compare_edge.argtypes = [c_void_p, c_void_p]    

No comments:

Post a Comment