Ctypes在python中构造数组
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))]
我试着创建一个main类的对象,并将指针转换为数组对象..
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, %dn", 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
>
相关文章:
- C++返回 Numpy 数组的 Python 扩展模块
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- C++未知长度字符串的数组,其行为类似于 Python 字符串列表
- Python C 绑定 - 获取从 python 到 C++ 的数组
- 如何使用列表/数组在C++中实现 Python "... not in ..."?
- 使用IPC/共享内存将Integer数组从C++传递到Python
- 如何使用 CTypes 将 wchar_t** - 以空结尾的 UNICODE 字符串数组 - 返回到 Python 脚
- 数组中未映射的内存访问从python传递到c++
- 数组数据以错误的方式遍历 Python/Matlab
- C++ & Python:传递并返回从 python 到 c++ 的 2D 双指针数组
- 将字节数组从 C++ 传递到 Python
- Python API用于解析包含数组格式的protobuf数据的二进制文件
- 使用 Boost.Python 将 numpy 数组传递给C++
- 在python swig中读取c ++ 2d数组
- 使用 Python、C++ 和 pybind11 返回并传递原始 POD 指针(数组)
- 如何在C 中创建类似于Python的Numpy数组的数组
- 使用套接字从 Python(客户端)发送到 C++(服务器)数组的数据
- C++相当于 Python 的:用于数组索引
- 使用CTYPE将数组从Python传递到C ,无法完全处理
- C++中的字符切片数组(python到c ++)