我正在尝试使用ctypes库将.cpp文件转换为.py
一些基本操作正在运行,但我在使用typedef结构和malloc/free时遇到了困难
这是我得到的:
模块h:
typedef struct
{
CHAR8 name[M_MODNAMELEN_A]; /**< Name of the module. */
} MODULE_NAME;
typedef struct
{
UINT16 countModules; /**< Count of module names.*/
MODULE_NAME * names; /**< Array of module names. */
} MODULE_LIST;
program.cpp:
UINT16 countModules;
SINT32 ret = GetCountModules(targetHandle, &countModules);
if(ret!=M1C_OK)
return ret;
MODULE_LIST modList;
modList.names = (MODULE_NAME*)malloc(countModules * sizeof(MODULE_NAME));
// do some calculations
free( modList.names );
program.py:
from ctypes import *
c_lib = CDLL('libXXYY.so')
class MODULE_NAME(Structure):
_fields_ = [
('name', c_byte)
]
def __repr__(self):
return '({0})'.format(self.name)
class MODULE_LIST(Structure):
_fields_ = [
('countModules', c_uint),
('names', POINTER(MODULE_NAME)) ### Is this conversion correct?
]
def __repr__(self):
return '({0}, {1})'.format(self.x, self.y)
count_modules = c_uint()
ret = c_long(c_lib.GetCountModules(target_handle, byref(count_modules)))
if ret.value != M1C_OK:
return ret
# Up to here everything works fine..
# Allocating memory for the list of module names
modList = MODULE_LIST()
modList.names = ### How to convert the malloc line?
## Some calcs
### How to convert the free( modList.names ); line?
python在“modList.names=”行中正常运行。。在那里,我尝试了几种方法(例如:modList.names=(MODULE_NAME)count_modules.value*sizeof(MODULE_NAME()),但我所有的尝试都失败了
如何将malloc行从cpp转换为python
我应该如何将自由行从cpp翻译成python
typedef结构到类的翻译是否正确?特别是“模块列表”
通常,返回类似MODULE_LIST的DLL会为您执行malloc, 并提供了一个函数来释放它以后,但如果你必须填写一个自己 数组类型是通过将类型乘以大小,然后调用它来创建实例来创建的:
如果如上所述进行分配,Python将在不再有对内存的引用时释放它,例如当上面的
m
超出范围时。您可以调用del m
来显式地取消对内存的引用。如果m
是唯一的引用,它将被释放否,
CHAR8 name[M_MODNAMELEN_A];
是一个数组,因此将一个类型乘以一个长度以生成正确的数组类型:MODULE_LIST
有一个16位整数,因此请使用正确的16位类型:要正确调用函数,最佳做法是为函数定义
.argtypes
和.restype
以改进错误检查:相关问题 更多 >
编程相关推荐