简体   繁体   English

将C结构传递给Python函数

[英]Passing a C struct to a Python function

I need a simple way to pass a C struct to a Python function. 我需要一种简单的方法来将C结构传递给Python函数。 I have embedded Python into a game server, and I intend to write game logic in Python. 我已经将Python嵌入到游戏服务器中,并且打算用Python编写游戏逻辑。 I've scoured Google and mailing lists and found nothing useful. 我搜寻了Google和邮件列表,发现没有任何用处。 I have a complex structure in C (with pointers to other relatively complex structures) and have found no reasonable way of doing this. 我在C语言中有一个复杂的结构(带有指向其他相对复杂结构的指针),并且没有找到实现此目的的合理方法。

I have this struct: 我有这个结构:

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 need to pass it to a Python function where I can easily access the members with common syntax (preferably not the use of things like dicts although that's alright too). 并且需要将其传递给Python函数,在这里我可以使用通用语法轻松访问成员(最好不要使用dict等东西,尽管也可以)。 It's almost like I need a PyObject_FromStruct function or something. 几乎就像我需要一个PyObject_FromStruct函数之类的。

Is there any relatively simple way to do this? 有没有相对简单的方法可以做到这一点?

SWIG can do pointers, especially if you can treat them as opaque blobs in your Python code. SWIG可以执行指针,特别是如果您可以在Python代码中将它们视为不透明的Blob。

You might also get somewhere with Cython - it's a dialect of Python that allows you to intermix Python and C datatypes. Cython可能还会使您有所作为-这是Python的方言,可让您混合使用Python和C数据类型。

最好的选择是swig ,但我认为指针会给您带来麻烦。

i think that the most simple way may be to write get()/set() functions for every element in the structure (ex: get_addr() which gets the address value) and then: 我认为最简单的方法可能是为结构中的每个元素编写get()/ set()函数(例如:get_addr()获取地址值),然后:

Option 1 (i think it is the simplest) :compile your c code as dll file with get/set exported and load it into python to call "get" functions (check my post here for using dll in python and this Q&A may be useful for using .so files in linux 选项1(我认为这是最简单的):将您的c代码编译为dll文件,并导出get / set并将其加载到python中,以调用“ get”函数(请在此处查看我的文章以在python中使用dll,此问与答可能会有用在Linux中使用.so文件

Option 2 :you may use SWIG to get the pyd file and import it into python to call "get/set" functions 选项2:您可以使用SWIG获取pyd文件并将其导入python以调用“获取/设置”功能

using this way python is dealing only with pointee NOT pointers and do not involve any memory addresses usage. 使用这种方式,python只处理pointee NOT指针,并且不涉及任何内存地址的使用。

I'd wrap the struct in something digestible by python with boost::python. 我会用boost :: python将结构体包装在python可消化的东西中。 And then access the functionality you want exported to python. 然后访问要导出到python的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM