Passing C function to Python function

I need an easy way to pass the C structure to a Python function. I have included Python in the game server and I intend to write the game logic in Python. I looked at Google and the mailing lists and found nothing useful. I have a complex structure in C (with pointers to other relatively complex structures) and have not found a reasonable way to do this.

I have this structure:

struct client { int state; int sockfd; struct sockaddr_in *addr; struct epoll_event *epollev; struct buffer *in_buffer; struct buffer *out_buffer; struct packet *packet; struct player *player; }; 

And you need to pass it to Python functions, where I can easily access elements with a common syntax (it is advisable not to use things like dicts, although this is also good). It is almost as if I needed the PyObject_FromStruct function or something like that.

Is there a relatively easy way to do this?

+4
source share
4 answers

I think the easiest way could be to write get () / set () functions for each element in the structure (for example: get_addr (), which gets the address value), and then:

Option 1 (I think this is the easiest): compile your c-code as a dll file with get / set and load it in python to call the get functions (check my post here for using dll in python, and this one Q & A can be useful for using .so files in linux

Option 2: you can use SWIG to get the pyd file and import it into python to call the get / install functions

using this method, python only deals with pointee pointer pointers and does not use memory addresses.

0
source

SWIG can do pointers, especially if you can think of them as opaque drops in Python code.

You can also get somewhere with Cython - this is a Python dialect that allows you to mix Python and C data types.

+2
source

Something like swig would be best, but I think pointers will give you problems.

0
source

I would wrap the structure in something that could be digested using python with boost :: python. And then access the functions you want to export to python.

0
source

Source: https://habr.com/ru/post/1387960/


All Articles