python ctypes是否支持size-0数组? [英] does python ctypes supports size-0 array?
本文介绍了python ctypes是否支持size-0数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我里面有一个带有array [0]的结构。我想知道如何用ctypes表示它?还是ctypes不支持它,还有其他解决方案吗?任何帮助将不胜感激。
i have a struct with array[0] inside it.i wonder how can i represent it with ctypes? or if ctypes does not supprt it, are there any other solutions? Any help will be appreciated.
推荐答案
您可以表示这样的结构:
You can represent a struct like this:
struct Test
{
int size;
char arr[0];
};
作为:
class Test(ctypes.Structure):
_fields_ = [('size',ctypes.c_int),
('arr',ctypes.c_byte*0)]
但是要访问该字段,您需要将其强制转换为指针。假设 t
的类型为 ctypes.POINTER(Test)
:
But to access the field, you'll need to cast it to a pointer. Assume t
is of type ctypes.POINTER(Test)
:
arr = ctypes.cast(t.contents.arr,POINTER(c_byte))
for i in range(t.contents.size):
print(arr[i])
经过测试的Windows示例
xh
#ifdef TESTAPI_EXPORTS
#define TESTAPI __declspec(dllexport)
#else
#define TESTAPI __declspec(dllimport)
#endif
struct Test
{
int size;
int arr[0];
};
TESTAPI struct Test* Test_alloc(int size);
TESTAPI void Test_free(struct Test* test);
xc(用 cl / LD xc编译)
x.c (Compile with "cl /LD x.c")
#include <stdlib.h>
#define TESTAPI_EXPORTS
#include "x.h"
struct Test* Test_alloc(int size)
{
struct Test* t = malloc(sizeof(struct Test) + size * sizeof(int));
if(t != NULL)
{
int i;
t->size = size;
for(i = 0; i < size; ++i)
t->arr[i] = i*1000+i;
}
return t;
}
void Test_free(struct Test* test)
{
free(test);
}
x.py
from ctypes import *
class Test(Structure):
_fields_ = [('size',c_int),
('arr',c_int*0)]
dll = CDLL('x')
Test_alloc = dll.Test_alloc
Test_alloc.argtypes = [c_int]
Test_alloc.restype = POINTER(Test)
Test_free = dll.Test_free
Test_free.argtypes = [POINTER(Test)]
Test_free.restype = None
t = Test_alloc(10)
print(t.contents.size)
arr = cast(t.contents.arr,POINTER(c_int))
for i in range(t.contents.size):
print(arr[i])
Test_free(t)
输出
10
0
1001
2002
3003
4004
5005
6006
7007
8008
9009
这篇关于python ctypes是否支持size-0数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文