0

I am attempting to write a .so library wrapper for an existing C source code project, and then call the functions in the .so library from Python. I have been able to call functions with primitive arguments and return types with no problem, so I am now working on interfacing with more complex functions that have arguments that are pointers to structures.

My problem is in creating the structures on the Python side so that I can call the C-library functions. Some of the structs in the .so library have hundreds of fields, so I was hoping there was an easier alternative to spelling out all the fields and types in a Python ctypes Structure object.

I would like to be able to write something like this is Python:

from ctypes import *

lib = cdll.LoadLibrary("./libexample.so")

class Input(Structure):
    _fields_ = lib.example_struct._fields  ## where `example_struct` is defined in the .so library
                     ## I have no idea if you can actually get the fields of the struct!!

my_input = Input(a,b,c,...)  ## pseudo-code
my_ptr = pointer(my_input)  ## wrap the input with a pointer
result = lib.my_lib_func(my_ptr)  ## call .so function with struct

This would allow me to easily replicate at least the structure definitions of the large C structs without having to create and maintain lengthy Python versions of the struct definitions. Is this possible? Or is there another way to achieve the same effect?

EDIT: The C source code is third party, so for now, I am looking for an approach where I don't have to modify the C source.

gariepy
  • 3,576
  • 6
  • 21
  • 34
  • *"structs [...] have hundreds of fields"* That's usually an indication of a design flaw. It may be more appropriate to use arrays. – user3386109 Mar 28 '16 at 22:15
  • Could be, but it isn't my code, so I'm trying to wrap it in a non-invasive way, if possible. – gariepy Mar 28 '16 at 22:17
  • @user3386109: There are very well such `structs`. But they are rare and for new code, some OOP approach with inheritance is often better. – too honest for this site Mar 28 '16 at 22:19
  • You have to fill the fields anyway, how would that work with automatic extraction from the library? – too honest for this site Mar 28 '16 at 22:21
  • That's true...for inputs there's no way around that, but some of the structs are for returning output values as well. – gariepy Mar 28 '16 at 22:25
  • is the so compiled with debug information? if so you could parse that. take a look at this http://stackoverflow.com/questions/1101272/library-to-read-elf-file-dwarf-debug-information – Tamas Hegedus Mar 28 '16 at 22:46

1 Answers1

0

The Cython approach is to read and interpret the .h header file. But I do not say it would be easy.

user3435121
  • 633
  • 4
  • 13