2

我想使用 ctypes 包装一个小型测试 C++ 类以在 python 中使用。该类被称为Edge并具有朋友比较 (==) 运算符。我很难在包装器 python 代码中实现比较功能。

一个简洁的Edge标题是:

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包装器是:

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++ 例程,定义为:

#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

我确实了解错误的含义,并且很可能会出现问题的原因,但我不知道如何解决。我正在用 gcc 4.7 编译 C++ 代码,python 解释器是 64 位的。

4

1 回答 1

3

问题是,您正在尝试将 Python 对象强制转换为 a void *,而不是void *您已经附加到该对象的obj属性。

它应该像改变一样简单......

def __eq__(self, other):
    return lib.compare_edge(self.obj, c_void_p(other))

...至...

def __eq__(self, other):
    return lib.compare_edge(self.obj, other.obj)

显式调用c_void_p应该是不必要的,因为您已经在该行中声明了类型...

lib.compare_edge.argtypes = [c_void_p, c_void_p]
于 2013-06-21T21:53:06.427 回答