ctypes c ++函数返回未知大小的数组 [英] ctypes c++ function returns array of unknown size

查看:94
本文介绍了ctypes c ++函数返回未知大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c ++函数,该函数接受指向已知大小的数组的Pointer作为输入,并返回在该函数完成数据处理之前无法确定的大小的数组.如何调用c ++函数,传递第一个数组并将结果作为第二个数组接收?

I have a c++ function that accepts a Pointer to an array of known size as input and returns an array of size that cannot be determined until the function completes its processing of data. How do I call the c++ function, passing the first array and receive the results as a second array?

我目前正在做类似的事情:

I currently do something similar to this:

PYTHON:

def callout(largeListUlonglongs):
    cFunc = PyDLL("./cFunction.dll").processNumbers

    arrayOfNums = c_ulonglong * len(largeListUlonglongs)
    numsArray = arrayOfNums()

    for x in xrange(len(largeListUlonglongs)):
        numsArray[x] = long(largeListUlonglongs[x])

    cFunc.restype = POINTER(c_ulonglong * len(largeListUlonglongs))

    returnArray = cFunc(byref(numsArray)).contents

    return returnArray

只要returnArray与numsArray的大小相同,此方法就起作用.如果较小,则用0填充数组的空元素.如果返回的数组大于结果,则一旦数组元素被填充,结果就会被截断.

This works so long as the returnArray is of the same size as the numsArray. If it is smaller then the empty elements of the array are filled with 0's. If the returned array is larger than the results get cut off once the array elements are filled.

如果有帮助,则返回数组的结构将返回数组的大小作为其第一个元素.

If it helps, the structure of the returned array contains the size of the returned array as its first element.

感谢您的提前帮助...

Thanks for the help in advance...

推荐答案

通常,最好让调用方分配缓冲区.这样,调用方也可以取消分配它.但是,在这种情况下,只有被叫方知道缓冲区需要多长时间.因此,举证责任传递给被调用方以分配缓冲区.

Normally it is preferable to get the caller to allocate the buffer. That way the caller is in a position to deallocate it also. However, in this case, only the callee knows how long the buffer needs to be. And so the onus passes to the callee to allocate the buffer.

但是,这对系统造成了额外的限制.由于被调用方正在分配缓冲区,因此除非调用方共享相同的分配器,否则调用方无法对其进行分配.实际上可以安排得没有太多麻烦.您可以使用共享分配器.有几个.您的平台似乎是Windows,因此例如您可以使用 CoTaskMemAlloc CoTaskMemFree .界面的两侧都可以调用这些函数.

But that places an extra constraint on the system. Since the callee is allocating the buffer, the caller cannot deallocate it unless they share the same allocator. That can actually be arranged without too much trouble. You can use a shared allocator. There are a few. Your platform appears to be Windows, so for example you can use CoTaskMemAlloc and CoTaskMemFree. Both sides of the interface can call those functions.

另一种方法是将分配和重新分配保持在一起.调用者必须保持被调用者返回的指针.完成缓冲区后,通常在将其复制到Python结构中之后,它会要求库取消分配内存.

The alternative is to keep allocation and deallocation together. The caller must hold on to the pointer that the callee returns. When it has finished with the buffer, usually after copying it into a Python structure, it asks the library to deallocate the memory.

这篇关于ctypes c ++函数返回未知大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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