[英]ctypes structure arrays in python
我正在嘗試創建一個指向嵌套結構數組的指針。 但是對於c ++,僅傳遞第一個結構元素...
C ++代碼:
typedef structure
{
int One;
int Two;
}nestedStru;
typedef structure
{
int First;
nestedStru* Poniter; //Pointer to nested structure array
}mainStru;
等效的python代碼:
class nestedStru(Structure)
_fields_ = [("One",c_uint8),
("Two",c_uint8)]
class mainStru(Structure):
_fields_ = [("First",c_uint8),
("PointerToNested",POINTER(nestedStru))]
我嘗試創建主類的對象,並將指針轉換為數組對象。
object = mainStru()
object.Second = cast((nestedStru * 2)(), POINTER(nestedStru))
歡迎大家提出意見。 提前致謝!
您使用c_uint8
(8位),而您的結構使用int
,通常使用c_int
ctypes 32位。
您的結構應為:
class nestedStru(Structure):
_fields_ = [
("One", c_int),
("Two", c_int)
]
class mainStru(Structure):
_fields_ = [
("First", c_int),
("Poniter", POINTER(nestedStru))
]
這是一個測試庫:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int One;
int Two;
} nestedStru;
typedef struct
{
int First;
nestedStru* Poniter; // Pointer to nested structure array
} mainStru;
void
func(const mainStru *obj, size_t s)
{
size_t i;
for( i = 0 ; i < s ; i++ )
{
printf("%d, %d\n", obj->Poniter[i].One, obj->Poniter[i].Two);
}
}
Python客戶端:
#!python
from ctypes import *
class nestedStru(Structure):
_fields_ = [
("One", c_int),
("Two", c_int)
]
class mainStru(Structure):
_fields_ = [
("First", c_int),
("Poniter", POINTER(nestedStru))
]
if __name__ == '__main__':
obj = mainStru()
obj.First = 0
obj.Poniter = (nestedStru * 3)((1, 11), (2, 22), (3, 33))
func = CDLL('./lib.dll').func
func.argtypes = [POINTER(mainStru), c_size_t]
func.restype = None
func(obj, 3)
現在工作正常:
> gcc -Wall lib.c -o lib.dll -shared
> python file.py
1, 11
2, 22
3, 33
>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.