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++对象销毁
基础教程推荐
猜你喜欢
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
