yel*_*cap 5 python arrays ctypes return gdal
我正在尝试使用 ctypes 包装一个 C 函数,它返回一个未知大小的字符数组。该函数来自 gdal c api,但我的问题并非特定于该函数。
我想知道是否有一种通用方法可以解构返回未知大小的 char** 数组对象的函数的输出。在 ctypes 中,这将是POINTER(c_char_p * X)
X 未知的地方。
# Define the function wrapper.
f = ctypes.CDLL('libgdal.so.20').GDALGetMetadata
MAX_OUTPUT_LENGTH = 10
f.restype = ctypes.POINTER(ctypes.c_char_p * MAX_OUTPUT_LENGTH)
f.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
# Example call (the second argument can be null).
result = []
counter = 0
output = f(ptr, None).contents[counter]
while output:
result.append(output)
counter += 1
output = f(ptr, None).contents[counter]
Run Code Online (Sandbox Code Playgroud)
output
结果数组在哪里,ptr
是指向打开的 GDALRaster 的 ctypes 指针。对此的限制是我必须在调用函数之前构造一个固定长度的数组。我可以猜测实际情况下的最大长度是多少,然后简单地使用它。但这是任意的,我想知道是否有一种方法可以在不指定数组长度的情况下获取数组指针。换句话说:
有没有办法做与上面的例子类似的事情,但没有指定任意的最大长度?
事实证明,如果函数输出是一个以 null 结尾的字符数组,则可以简单地将指针传递给c_char_p
对象,而无需指定长度作为 restype 参数。然后循环遍历结果,直到找到 null 元素,这表示数组的末尾。
因此,以下内容非常适合我的用例:
# Define the function wrapper, the restype can simply be a
# pointer to c_char_p (without length!).
f = ctypes.CDLL('libgdal.so.20').GDALGetMetadata
f.restype = ctypes.POINTER(ctypes.c_char_p)
f.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
# Prepare python result array.
result = []
# Call C function.
output = f(ptr, None)
# Ensure that output is not a null pointer.
if output:
# Get first item from array.
counter = 0
item = output[counter]
# Get more items, until the array accessor returns null.
# The function output (at least in my use case) is a null
# terminated char array.
while item:
result.append(item)
counter += 1
item = output[counter]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
970 次 |
最近记录: |