代码之家  ›  专栏  ›  技术社区  ›  tauran

Python cType,C++对象破坏

  •  4
  • tauran  · 技术社区  · 14 年前

    // C++
    class A
    {
    public:
        void someFunc();
    };
    
    A* A_new() { return new A(); }
    void A_someFunc(A* obj) { obj->someFunc(); }
    void A_destruct(A* obj) { delete obj; }
    
    # python
    from ctypes import cdll
    
    libA = cdll.LoadLibrary(some_path)
    
    class A:
        def __init__(self):
            self.obj = libA.A_new()
    
        def some_func(self):
            libA.A_someFunc(self.obj)
    

    当不再需要python对象时,删除c++对象的最佳方法是什么。

    我添加了建议的delete函数,但是问题仍然是由谁和何时调用该函数。应该尽可能方便。

    3 回复  |  直到 14 年前
        1
  •  10
  •   Just a student    4 年前

    你可以实现 __del__ 方法调用您必须定义的析构函数:

    C++

    class A
    {
    public:
        void someFunc();
    };
    
    A* A_new() { return new A(); }
    void delete_A(A* obj) { delete obj; }
    void A_someFunc(A* obj) { obj->someFunc(); }
    

    from ctypes import cdll
    
    libA = cdll.LoadLibrary(some_path)
    
    class A:
        def __init__(self):
            fun = libA.A_new
            fun.argtypes = []
            fun.restype = ctypes.c_void_p
            self.obj = fun()
    
        def __del__(self):
            fun = libA.delete_A
            fun.argtypes = [ctypes.c_void_p]
            fun.restype = None
            fun(self.obj)
    
        def some_func(self):
            fun = libA.A_someFunc
            fun.argtypes = [ctypes.c_void_p]
            fun.restype = None
            fun(self.obj)
    

    self __init__ 方法。此外,还必须显式指定返回类型/参数类型,因为ctypes默认为32位整数,而在现代系统中,指针可能是64位的。

    有人认为 __德尔__ with 语法:

    class A:
        def __init__(self):
            fun = libA.A_new
            fun.argtypes = []
            fun.restype = ctypes.c_void_p
            self.obj = fun()
    
        def __enter__(self):
            return self
    
        def __exit__(self):
            fun = libA.delete_A
            fun.argtypes = [ctypes.c_void_p]
            fun.restype = None
            fun(self.obj)
    
        def some_func(self):
            fun = libA.A_someFunc
            fun.argtypes = [ctypes.c_void_p]
            fun.restype = None
            fun(self.obj)
    
    with A() as a:
        # Do some work
        a.some_func()
    
        2
  •  2
  •   Björn Pollex    14 年前

    一般来说,DLL应该提供一种方法来清理它们创建的对象。这样,内存分配就封装在dll中。这意味着,您的dll可能应该公开一个类似 void A_delete(A*) .

        3
  •  2
  •   Jim Brissom    14 年前