Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
832 views
in Technique[技术] by (71.8m points)

python - ctypes struct containing arrays

I'm trying to use ctypes. I'm interested in manipulating C structs containing arrays. Consider the following 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
",array_struct.first_array[i]);
    }

}

and suppose I've compiled it in a shared library my_so_object.so From Python I can do something like this

import ctypes
from ctypes import *

myLib = CDLL("c/bin/my_so_object.so")


class ArrayStruct(ctypes.Structure):
    _fields_ = [('first_array', ctypes.c_int * 10), ('second_array', ctypes.c_int * 10)]

    def __repr__(self):
        return 'ciaone'


myLib.print_array_struct.restype = None
myLib.print_array_struct.argtype = ArrayStruct

my_array_type = ctypes.c_int * 10
x1 = my_array_type()
x2 = my_array_type()

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

x1[0:9] = a[0:9]

a = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

x2[0:9] = a[0:9]

print(my_array_type)
>>> <class '__main__.c_int_Array_10'>

print(x1[2])
>>> 3

print(x2[2])
>>> 13

x = ArrayStruct(x1, x2)

print(x.first_array[0:9])
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]

So far so good: I've created the correct types and everything seems working fine. But then:

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

I'm clearly missing something. The ArrayStruct type is recognized (otherwise the call myLib.print_array_struct(x) would throw an error) but not correctly initialized.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There were 2 problems with the code (as I stated in the comment):

  1. print_array_struct.argtype - which is incorrect
  2. In C the arrays are double based, while in Python they are ctypes.c_int (int) based

For more details, check [Python 3.Docs]: ctypes - A foreign function library for Python.
I modified your Python code, to correct the above mistakes (and some other minor stuff).

code00.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}
".format(sys.version, sys.platform))
    main()

Output:

[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q050447199]> python3 code00.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



Update #0

Error #1. is a "duplicate" of (newer) [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...