如何保存包含指针的ctypes对象 [英] How to save ctypes objects containing pointers

查看:607
本文介绍了如何保存包含指针的ctypes对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用第三方库,该库在经过大量计算后会返回包含指针的ctypes对象.

I use a 3rd party library which returns after a lot of computation a ctypes object containing pointers.

如何保存ctypes对象以及指针指向的对象以供以后使用? 我尝试过

How can I save the ctypes object and what the pointers are pointing to for later use? I tried

  • scipy.io.savemat => TypeError:无法将对象转换为数组
  • cPickle =>不能腌制包含指针的ctypes对象
  • scipy.io.savemat => TypeError: Could not convert object to array
  • cPickle => ctypes objects containing pointers cannot be pickled

推荐答案

Python无法自动为您完成此操作:

Python has no way of doing that automatically for you:

您将必须构建代码以自行选择所有所需数据,然后将它们放入合适的Python数据结构中(或仅将数据添加到唯一的字节字符串中,在此您将知道每个元素的偏移量在哪里)-然后将该对象保存到磁盘.

You will have to build code to pick all the desired Data yourself, putting them in a suitable Python data structure (or just adding the data in a unique bytes-string where you will know where each element is by its offset) - and then save that object to disk.

这不是"Python"问题-恰恰是使用Python对象和数据时Python为您解决的问题.当使用C或更低级别的代码进行编码时,您不仅要知道数据在哪里,还要知道每个数据块的长度(并为每个块分配内存,并在完成时释放它,等等).在这种情况下,这就是您要做的.

This is not a "Python" problem - it is exactly a problem Python solves for you when you use Python objects and data. When coding in C or lower level, you are responsible to know not only where your data is, but also, the length of each chunk of data (and allocate memory for each chunk, and free it when done, and etc). And this is what you have to do in this case.

您的数据结构不仅应为您提供指针,还应为每个指向的位置提供数据长度(以某种方式-如果指针指向另一个结构,则"size_of"将为您工作)

Your data structure should give you not only the pointers, but also the length of the data in each pointed location (in a way or the other - if the pointer is to another structure, "size_of" will work for you)

这篇关于如何保存包含指针的ctypes对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆