包含数组的ctypes结构

2024-09-28 19:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用ctypes。我对操作包含数组的C结构感兴趣。考虑以下my_library.c

#include <stdio.h>


typedef struct {

    double first_array[10];
    double second_array[10];

} ArrayStruct;


void print_array_struct(ArrayStruct array_struct){

    for (int i = 0; i < 10; i++){
        printf("%f\n",array_struct.first_array[i]);
    }

}

假设我在Python的一个共享库my_so_object.so中编译了它,我可以这样做

^{pr2}$

到目前为止还不错:我已经创建了正确的类型,一切看起来都很好。但随后:

myLib.print_array_struct(x)
>>> 0.000000
>>> 0.000000 
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000

我显然漏掉了什么。已识别ArrayStruct类型(否则调用myLib.print_array_struct(x)将引发错误),但未正确初始化。在


Tags: 类型somylibrary数组ctypes结构array
1条回答
网友
1楼 · 发布于 2024-09-28 19:35:21

代码有两个问题(正如我在评论中所说):

  • print_array_struct.argtype-哪个不正确
  • C中,数组是基于的,而在Python中,它们是基于ctypes.c_intint)的

有关详细信息,请选中[Python 3]: ctypes - A foreign function library for Python
我修改了您的Python代码,以纠正上述错误(以及其他一些小问题)。在

代码.py

#!/usr/bin/env python3

import sys
import ctypes


DLL_NAME = "./my_so_object.so"

DOUBLE_10 = ctypes.c_double * 10

class ArrayStruct(ctypes.Structure):
    _fields_ = [
        ("first_array", DOUBLE_10),
        ("second_array", DOUBLE_10),
    ]


def main():
    dll_handle = ctypes.CDLL(DLL_NAME)
    print_array_struct_func = dll_handle.print_array_struct
    print_array_struct_func.argtypes = [ArrayStruct]
    print_array_struct_func.restype = None

    x1 = DOUBLE_10()
    x2 = DOUBLE_10()
    x1[:] = range(1, 11)
    x2[:] = range(11, 21)
    print([item for item in x1])
    print([item for item in x2])
    arg = ArrayStruct(x1, x2)
    print_array_struct_func(arg)


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

输出

[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q050447199]> python3 code.py
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
[11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0]
1.000000
2.000000
3.000000
4.000000
5.000000
6.000000
7.000000
8.000000
9.000000
10.000000

相关问题 更多 >