传递一个C结构到Python功能 [英] Passing a C struct to a Python function

查看:167
本文介绍了传递一个C结构到Python功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单的方法来一个C结构传递给Python函数。我已经嵌入式Python到游戏服务器,我打算写游戏逻辑在Python。我已经冲刷谷歌和邮件列表,没有发现任何有用的。我有在C复杂的结构(具有指向其他相对复杂的结构),并发现这样做的合理途径。

I need a simple way to pass a C struct to a Python function. I have embedded Python into a game server, and I intend to write game logic in Python. I've scoured Google and mailing lists and found nothing useful. I have a complex structure in C (with pointers to other relatively complex structures) and have found no reasonable way of doing this.

我有这样的结构:

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;
};

和需要将它传递给一个Python函数,我可以很容易地与常用的语法访问成员(preferably不使用的东西一样类型的字典,虽然这是正常的太)。这几乎就像我需要PyObject_FromStruct功能什么的。

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). It's almost like I need a PyObject_FromStruct function or something.

有没有比较简单的方法来做到这一点?

Is there any relatively simple way to do this?

推荐答案

我认为最简单的方法是写一个获得()/()设置为每个元素功能结构(例如:GET_ADDR(),它获取的地址值),然后

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:

选项1(我认为这是最简单的):编译C code与出口的get / set dll文件并将其加载到蟒蛇叫搞定功能
(检查我的文章<一个href=\"http://stackoverflow.com/questions/8262884/python-c-extension-use-extension-pyd-or-dll/8520691#8520691\">here在使用Python中的dll,这<一个href=\"http://stackoverflow.com/questions/1777752/python-importing-using-cdll-with-a-linux-so-file\">Q&A可以使用。所以Linux中的文件是有用的。

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

选项2:您可以使用SWIG来获取PYD文件,并将其导入到蟒蛇叫获取/设置功能

Option 2 :you may use SWIG to get the pyd file and import it into python to call "get/set" functions

使用这种方式蟒蛇与指针对象不是指针只处理,不涉及任何内存地址的使用情况。

using this way python is dealing only with pointee NOT pointers and do not involve any memory addresses usage.

这篇关于传递一个C结构到Python功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆