Python ctypes,C ++对象破坏

时间:2010-09-16 08:34:11

标签: c++ python ctypes

考虑以下python ctypes - c ++绑定:

// 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 ++对象的最佳方法是什么。

[编辑] 我添加了建议的删除功能,但问题仍然是由谁以及何时调用该函数。它应该尽可能方便。

3 个答案:

答案 0 :(得分:8)

您可以实现__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(); }

<强>的Python

from ctypes import cdll

libA = cdll.LoadLibrary(some_path)

class A:
    def __init__(self):
        self.obj = libA.A_new()

    def __del__(self):
        libA.delete_A(self.obj)

    def some_func(self):
        libA.A_someFunc(self.obj)

另请注意,您在self方法中遗漏了__init__参数。

有些人认为__del__是邪恶的。作为替代方案,您可以使用with语法:

class A:
    def __init__(self):
        self.obj = libA.A_new()

    def __enter__(self):
        return self

    def __exit__(self):
        libA.delete_A(self.obj)

    def some_func(self):
        libA.A_someFunc(self.obj)

with A() as a:
    # Do some work
    a.some_func()

答案 1 :(得分:2)

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

答案 2 :(得分:2)

从DLL导出函数释放对象。您必须这样做才能确保在分配对象时使用相同的内存管理机制来释放负责的对象。

相关问题