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++对象销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:Python ctype,C++对象销毁
基础教程推荐
猜你喜欢
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
