gpt4 book ai didi

python - python中的ctypes结构数组

转载 作者:行者123 更新时间:2023-11-30 04:07:10 24 4
gpt4 key购买 nike

我正在尝试创建一个指向嵌套结构数组的指针。但是对于 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,在ctypes c_int中,通常是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
>

关于python - python中的ctypes结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22582846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com