Python ctype,C++对象销毁

Python ctypes, C++ object destruction(Python ctype,C++对象销毁)
本文介绍了Python ctype,C++对象销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下python ctype-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)

删除C++对象的最佳方式是什么,因为不再需要该对象。

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

推荐答案

您可以实现__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):
        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)
还请注意,您遗漏了__init__方法上的self参数。此外,您必须显式指定返回类型/参数类型,因为ctype默认为32位整数,而在现代系统上指针可能为64位。

有些人认为__del__是邪恶的。或者,您可以使用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, exc_type, exc_val, exc_tb):
        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()

这篇关于Python ctype,C++对象销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Boost module machine type #39;X86#39; conflicts with target machine type #39;x64#39;(Boost模块计算机类型#39;x86#39;与目标计算机类型#39;x64#39;)
Trouble running LLVM examples(运行LLVM示例时出现问题)
Linker error while linking some windows APIs(链接某些Windows API时出现链接器错误)
DllGetClassObject return amp;quot;No such interface supportedamp;quot; while CoCreateInstance can find it successful(DllGetClassObject返回amp;不支持这样的接口,而CoCreateInstance发现它成功了)
Is static_castamp;lt;doubleamp;gt;(std::nanf(amp;quot;amp;quot;)) well defined?(Static_castamp;lt;doubleamp;gt;(std::nanf(amp;quot;amp;quot;))是否定义良好?)
How do I compare a std::function#39;s target with a member function#39;s address?(如何将std::函数的目标与成员函数的地址进行比较?)