1

I'm trying to have a pointer created to nested structure array. But to c++ only first structure elements are passed...

C++ code:

typedef structure
{
int One;
int Two;
}nestedStru; 

typedef structure
{
int First;
nestedStru* Poniter; //Pointer to nested structure array
}mainStru;

Equivalent python code:

class nestedStru(Structure)
    _fields_ = [("One",c_uint8),          
        ("Two",c_uint8)]

class mainStru(Structure):
    _fields_ = [("First",c_uint8),
                ("PointerToNested",POINTER(nestedStru))] 

I tried creating an object of main class and cast pointer to array objects..

object = mainStru()
object.Second = cast((nestedStru * 2)(), POINTER(nestedStru)) 

Any suggestions would be welcome. Thanks in advance!

2
  • 1
    What's your question? does it throw an error? Commented Mar 22, 2014 at 20:02
  • object.Second[0].One = 8 object.Second[0].Two = 1 object.Second[1].One = 8 object.Second[1].Two = 1 If I pass this object through a function to C++ code using byref , second structure elements are not passed No error is thrown Commented Mar 22, 2014 at 20:05

1 Answer 1

2

You use c_uint8, which is 8-bit, while your structure uses int, in ctypes c_int, usually 32-bit.

Your structures should be:

class nestedStru(Structure):
    _fields_ = [
      ("One", c_int),          
      ("Two", c_int)
    ]

class mainStru(Structure):
    _fields_ = [
      ("First", c_int),
      ("Poniter", POINTER(nestedStru))
    ]

This is a test library:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  int One;
  int Two;
} nestedStru; 

typedef struct
{
  int First;
  nestedStru* Poniter; // Pointer to nested structure array
} mainStru;

void
func(const mainStru *obj, size_t s)
{
  size_t i;

  for( i = 0 ; i < s ; i++ )
  {
    printf("%d, %d\n", obj->Poniter[i].One, obj->Poniter[i].Two);
  }
}

Python client:

#!python
from ctypes import *

class nestedStru(Structure):
    _fields_ = [
      ("One", c_int),          
      ("Two", c_int)
    ]

class mainStru(Structure):
    _fields_ = [
      ("First", c_int),
      ("Poniter", POINTER(nestedStru))
    ]

if __name__ == '__main__':
    obj = mainStru()
    obj.First = 0
    obj.Poniter = (nestedStru * 3)((1, 11), (2, 22), (3, 33))

    func = CDLL('./lib.dll').func
    func.argtypes = [POINTER(mainStru), c_size_t]
    func.restype = None

    func(obj, 3)

now it works fine:

> gcc -Wall lib.c -o lib.dll -shared
> python file.py
1, 11
2, 22
3, 33
>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.