Just create a pointer, assign the data afterwards;

import ctypes

class EmxArray(ctypes.Structure):
    """ creates a struct to match emxArray_real_T """

    _fields_ = [('data', ctypes.POINTER(ctypes.c_double)),
                ('size', ctypes.POINTER(ctypes.c_int)),
                ('allocatedSize', ctypes.c_int),
                ('numDimensions', ctypes.c_int),
                ('canFreeData', ctypes.c_bool)]

data = (1.3, 3.5, 2.7, 4.1)
L = len(data)

e = EmxArray()
e.data = (ctypes.c_double * L)(*data)
e.size = (ctypes.c_int * 1)(L)
# et cetera
Answer from Roland Smith on Stack Overflow
🌐
Python
docs.python.org › 3 › library › ctypes.html
ctypes — A foreign function library for Python
Here is an example of a somewhat artificial data type, a structure containing 4 POINTs among other stuff: >>> from ctypes import * >>> class POINT(Structure): ... _fields_ = ("x", c_int), ("y", c_int) ... >>> class MyStruct(Structure): ... _fields_ = [("a", c_int), ...
🌐
SageMath
doc.sagemath.org › html › en › thematic_tutorials › numerical_sage › ctypes_examples.html
More complicated ctypes example - Thematic Tutorials
Let’s discuss the above code. The original C code stored a sparse matrix as a linked list. The python code uses the ctypes Structure class to create structures mirroring the structs in the C code. To create python object representing a C struct, simply create class that derives from Structure.
Top answer
1 of 2
15

Just create a pointer, assign the data afterwards;

import ctypes

class EmxArray(ctypes.Structure):
    """ creates a struct to match emxArray_real_T """

    _fields_ = [('data', ctypes.POINTER(ctypes.c_double)),
                ('size', ctypes.POINTER(ctypes.c_int)),
                ('allocatedSize', ctypes.c_int),
                ('numDimensions', ctypes.c_int),
                ('canFreeData', ctypes.c_bool)]

data = (1.3, 3.5, 2.7, 4.1)
L = len(data)

e = EmxArray()
e.data = (ctypes.c_double * L)(*data)
e.size = (ctypes.c_int * 1)(L)
# et cetera
2 of 2
4

I'm not well-versed with the Python-C interface, so what I'm suggesting may be less than ideal. My guess is that likely the crash is because x->data is never initialized and the memory to which it is pointing isn't allocated.

An approach I have taken when interfacing to MATLAB Coder generated code from other languages in the presence of emxArray arguments is to hand-write a C interface function that provides a simpler API. This relieves the burden of needing to construct an emxArray in the other environment (Android Java in my particular case). If the generated function foo takes and returns a 2-D double array, then something like the following could work:

void foo(double *x, int *szx, double **y, int *szy);

This function would take a pointer to the input data and its size and provide a pointer to the output data and its size. The implementation would look something like:

void foo(double *x, int *szx, double **y, int *szy) 
{
  emxArray_real_T *pEmx;
  emxArray_real_T *pEmy;

  /* Create input emxArray assuming 2-dimensional input */
  pEmx = emxCreateWrapper_real_T(x, szx[0], szx[1]);

  /* Create output emxArray (assumes that the output is not */
  /* written before allocation occurs) assuming 2-D output  */
  pEmy = emxCreateWrapper_real_T(NULL, 0, 0);

  /* Call generated code (call foobar_initialize/terminate elsewhere) */
  foobar(pEmx, pEmy);

  /* Unpack result - You may want to MALLOC storage in *y and */
  /* MEMCPY there alternatively                               */
  *y = pEmy->data;
  szy[0] = pEmy->size[0];
  szy[1] = pEmy->size[1];

  /* Clean up any memory allocated in the emxArrays (e.g. the size vectors) */
  emxDestroyArray_real_T(pEmx);
  emxDestroyArray_real_T(pEmy);
}

You should be able to call this function from Python more simply and pass in the desired data as needed.

My other answer has more details on the emxArray_* functions found in the file foobar_emxAPI.h.

🌐
Samuelstevens
samuelstevens.me › writing › optimizing-python-code-with-ctypes
Optimizing Python Code with ctypes
All structs are classes that inherit from ctypes.Structure. The only field is _fields_, which is a list of tuples. Each tuple is (<variable-name>, <ctypes.TYPE>). ctypes has types like c_char (char), and c_char_p (*char). ctypes also includes POINTER() which creates a pointer type from any ...
🌐
ProgramCreek
programcreek.com › python › example › 1122 › ctypes.Structure
Python Examples of ctypes.Structure
def __init__(self, **kwargs): """ Ctypes.Structure with integrated default values. https://stackoverflow.com/questions/7946519/default-values-in-a-ctypes-structure/25892189#25892189 :param kwargs: values different to defaults :type kwargs: dict """ # sanity checks defaults = type(self)._defaults_ assert type(defaults) is types.DictionaryType # use defaults, but override with keyword arguments, if any values = defaults.copy() for (key, val) in kwargs.items(): values[key] = val # appropriately initialize ctypes.Structure #super().__init__(**values) # Python 3 syntax return Structure.__init__(self, **values) # Python 2 syntax # http://stackoverflow.com/questions/1825715/how-to-pack-and-unpack-using-ctypes-structure-str/1827666#1827666 # https://wiki.python.org/moin/ctypes
🌐
Stanford
sporadic.stanford.edu › thematic_tutorials › numerical_sage › ctypes_examples.html
More complicated ctypes example — Thematic Tutorials v9.3.beta9
Let’s discuss the above code. The original C code stored a sparse matrix as a linked list. The python code uses the ctypes Structure class to create structures mirroring the structs in the C code. To create python object representing a C struct, simply create class that derives from Structure.
🌐
dbader.org
dbader.org › blog › python-ctypes-tutorial-part-2
Interfacing Python and C: Advanced “ctypes” Features – dbader.org
November 7, 2017 - As you can see above, we make use of the _fields_ attribute of the class. Please note the single underscore—this is not a “dunder” function. This attribute is a list of tuples and allows ctypes to map attributes from Python back to the underlying C structure.
🌐
CodersLegacy
coderslegacy.com › home › structs with python ctypes
Structs with Python Ctypes - CodersLegacy
October 30, 2022 - A “struct” in Python is actually just a Class which we inherit from ctypes.Structure.
Find elsewhere
🌐
Python.org
discuss.python.org › python help
ctypes.Structure and bitfields - Python Help - Discussions on Python.org
March 20, 2023 - I have been using bit-fields with ctypes.Structure. I have a bitfield struct, and my issue is that no matter what I do, I am unable to set the values for my fields. A structure with the following definition: from ctypes import Structure, c_byte, c_int class Demo (Structure): _fields_ = [ ('f1', c_byte, 8), ('f2', c_int, 21), ('f3', c_byte, 2), ('f4', c_byte, 1) ] I have set the above struct using from_buffer_copy with a value of b'\x01\x0f\x00\xe0' (Binary representation of C struc...
🌐
Medium
medium.com › @datasciencefilmmaker › my-god-its-full-of-stars-2-d75d01d2cb94
My God, It’s Full of Stars (2/7) — Accessing C Structures in Python Using Ctypes | by Data Science Filmmaker | Medium
January 18, 2024 - Now we switch over to Python. ... 7) Declare a class based on “ctypes.Structure” and set the “_fields_” attribute to a list that matches the structure members as declared in C:
🌐
Iotexpert
iotexpert.com › stupid-python-tricks-c-structures-using-the-ctypes-module-part-2
Stupid Python Tricks: C-Structures using the ctypes Module (part 2) – IoT Expert
import ctypes class MyStruct(ctypes.BigEndianStructure): _pack_ = 1 _fields_ = [ ("first",ctypes.c_uint8,4), ("second",ctypes.c_uint8,4), ("third",ctypes.c_uint8,8), ] # Create a blank MyStruct a = MyStruct() a.first = 0xa a.second = 0xb a.third = 0xcd print(bytes(a)) When I run this you can see that indeed I get 0xABCD as the result. Several comments about this: Notice that it is BigEndian (which is good since that is what I declared) 0xA = 4-bits, 0-xB=4-bit so 0xAB is the first byte. ... You can also create a new structure by calling the class method “from_buffer_copy” with parameter of bytes type.
🌐
Pendancer
python.pendancer.com › advanced › ctypes.html
CTypes and Structures - Python
Below is an example of how to create a C struct using Python ctypes · import ctypes # Create the struct class P_Struct(ctypes.Structure): _fields_ = [("field_1", ctypes.c_int), ("field_2", ctypes.c_char_p)] # Pass struct values my_struct = P_Struct(1, "Hello World") # Create a pointer to my_struct pointer_my_struct = ctypes.pointer(my_struct) print my_struct.field_1, my_struct.field_2 # Import the DLL and pass pointer_my_struct to the C function requiring a pointer to a struct.
🌐
GitHub
github.com › nixawk › hello-python3 › blob › master › ctypes › ctypes.Structure.py
hello-python3/ctypes/ctypes.Structure.py at master · nixawk/hello-python3
#!/usr/bin/python · # -*- coding: utf-8 -*- · from ctypes import * · · """ class ctypes.Structure(*args, **kw) · Abstract base class for structures in native byte order.
Author: nixawk
🌐
Wumb0
wumb0.in › a-better-way-to-work-with-raw-data-types-in-python.html
A Better Way to Work with Raw Data Types in Python - wumb0in'
March 11, 2017 - Python's ctypes module can help you here. It has LittleEndianStructure and BigEndianStructure classes that will help turn the above code into something more usable and readable.
🌐
Python.org
discuss.python.org › python help
Can I figure out the type of a `ctypes` field? - Python Help - Discussions on Python.org
July 23, 2024 - I also have matching set of ctypes.Structure definitions where there is a specific subclass of ctypes.Structure for each section. Basically, each config file section defines settings for objects which are created in a C extension.
🌐
YouTube
youtube.com › coderslegacy
Using Structs and Classes with Python Ctypes - YouTube
In this Video, we will explore how to create, pass and return Structs between our C and Python program using the ctypes library. C File Compilation Code:gcc ...
Published: November 18, 2022
Views: 5K
🌐
Runebook.dev
runebook.dev › en › docs › python › library › ctypes › ctypes.Structure._pack_
python - Avoiding Padding Pitfalls: A Guide to ctypes Structure Alignment
In C programming (and thus ctypes), the compiler often adds invisible "gaps" or padding between structure members to ensure that each member starts at a memory address that's a multiple of its size (or a standard alignment value for the system). This is done for performance—accessing naturally aligned data is faster. Default Behavior (No _pack_) ctypes tries to match your system's default C compiler behavior, inserting padding. When to Use _pack_ When you need your Python structure to exactly match a C structure defined with a specific alignment (like using #pragma pack(1) in C) or when you're working with binary data formats (like network packets or file headers) that are tightly packed without any padding.
🌐
University of Chicago
people.cs.uchicago.edu › ~amr › 122 › labs › cstructs.html
CMSC 12200 - Structs in C and bridging with Python using CTypes - Februrary 2, 2011
We will acclimate ourselves with Structs and pointers to structs in C. We'll directly compare this to object oriented programming in Java and Python. We'll use CTypes to make fast functions written in C accessible within Python.