2
#include <stdio.h>

struct struct_data {
    int price;
    char list[255];
    int count;
};

__declspec(dllexport) void __stdcall testcall(struct struct_data *array_data) {

    int i = 0;
    while(array_data[i].price != 0) {           // array_data is guaranteed to have a zero somewhere inside memory allocated for the array
        printf("%d\n", array_data[i].price);
        i++;
    }

}

I try to call it from Python using cpython as follows:

# C Backend imports
import os
import sys
import ctypes

# load DLL
dll = ctypes.WinDLL('C:\\Users\\user\Documents\\Pelles C Projects\\MarketlibDLL\\MarketlibDLL.dll')

class struct_data(ctypes.Structure):
    _fields_ = [
        ('price', ctypes.c_int),
        ('list', ctypes.c_char * 255),
        ('count', ctypes.c_int),
    ]

d = struct_data() * 100    # I try to do:   struct struct_data d[100]; 
d[0].price = 100
d[0].list = "ABC"
d[0].count = 3
d[1].price = 0

dll.testcall.argtypes = [ctypes.POINTER(struct_data)]
dll.testcall(d)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-36161e840b5f> in <module>
----> 1 d = struct_data() * 100
      2 d[0].price = 100
      3 d[0].list = "ABC"
      4 d[0].count = 3
      5 d[1].price = 0

TypeError: unsupported operand type(s) for *: 'struct_data' and 'int'
1
  • @golobich see edited answer, I am trying to create a 100 items array of struct_data's that I can pass to the C function Commented Aug 25, 2019 at 11:37

2 Answers 2

2

[Python 3.Docs]: ctypes - A foreign function library for Python has all the required info (the Arrays section contains an example that maps perfectly over the current scenario).

Modify your code to (split in 2 lines for readability):

struct_data_array_100 = struct_data * 100  # !!! This is a type (array consisting of 100 struct_data elements) !!!
d = struct_data_array_100()  # Instantiate the array type
#d[0].price ...
# ...
Sign up to request clarification or add additional context in comments.

Comments

0

if you want a list of 100 struct_data you need to multiply the list not the data:

d = [struct_data()] * 100

This is the same as writing:

d = [struct_data() for _ in range(100)]

1 Comment

I want a C array of 100 struct_data objects, which is different from a list. I finally learned I have to do this: d = (struct_data * 100)()

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.