2

I have the below arrays on C how can i interpert them to ctypes datatypes inside structre

struct a {

BYTE    a[30];
CHAR    b[256];
};

should i interpert a fixed array as the datatype * the size i want like the below and if yes how can i call this structure as a parameter to fun that takes instance from this structure

class a(structure) :

_fields_ = [ ("a",c_bytes*30 ),
                 ("b",c_char*256 ),]

2 Answers 2

3

You're on the right track. You're probably just missing the byref() function. Assuming the function you want to call is named *print_struct*, do the following:

from ctypes import *

class MyStruct(Structure):
    _fields_ = [('a',c_byte*30), ('b',c_char*256)]

s = MyStruct() # Allocates a new instance of the structure from Python

s.a[5] = 10 # Use as normal

d = CDLL('yourdll.so')
d.print_struct( byref(s) )  # byref() passes a pointer rather than passing by copy
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

from ctypes import Structure, c_bytes, c_char

class A(Structure):
    _fields_ = [("a", c_bytes*30), ("b", c_char*256)]

Then you can simply access the fields of the structure using the dot operator:

>>> my_a = A()
>>> my_a.a[4] = 127
>>> my_a.a[4]
127
>>> my_a.b = "test string"
>>> my_a.b
'test string'
>>> my_a.b[2]
's'

You can also pass the structure directly to an arbitrary Python function:

def my_func(a):
    print "a[0] + a[1] = %d" % (a.a[0] + a.a[1], )
    print "Length of b = %d" % len(a.b)

>>> my_a = A()
>>> my_a.a[0:2] = 19, 23
>>> my_a.b = "test"
>>> my_func(my_a)
a[0] + a[1] = 42
Length of b = 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.