你如何调用从C code的Python code? [英] How do you call Python code from C code?
问题描述
我想用一些新的功能扩展大型C项目,但我真的想将它用Python语言编写。基本上,我想打电话从C code的Python code。然而,Python->Ç包装像SWIG允许的对面,即编写C模块,并在Python调用C
I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.
我在考虑涉及IPC或RPC(我不介意有多个进程)的方法;也就是说,有我的纯Python组件运行在单独的进程(在同一台机器上),并有我的C项目通过写/从插座(或UNIX管道),阅读与它通信。我的Python组件可以读/写套接字进行通信。那是一个合理的做法?是否有更好的东西?像一些特殊的RPC机制?
I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?
感谢您的回答至今 - 不过,我想专注于基于IPC的方法,因为我想有我的Python程序在一个单独的进程作为我的C程序。我不希望嵌入一个Python间preTER。谢谢!
Thanks for the answer so far - however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!
推荐答案
我推荐的办法赘述一>。它首先解释如何执行Python code的字符串,然后从那里详细介绍了如何建立一个Python环境与C程序交互,从C code调用Python函数,从C操纵Python对象code等。
I recommend the approaches detailed here. It starts by explaining how to execute strings of Python code, then from there details how to set up a Python environment to interact with your C program, call Python functions from your C code, manipulate Python objects from your C code, etc.
修改:如果你真的想去IPC的路线,然后你要使用的的结构模块或更好,但 protlib 。一个Python和C之间的进程通信的大多数路过周围围绕结构来回,要么通过套接字或通过共享内存。
EDIT: If you really want to go the route of IPC, then you'll want to use the struct module or better yet, protlib. Most communication between a Python and C process revolves around passing structs back and forth, either over a socket or through shared memory.
我建议创建带有字段命令
struct和codeS重新present命令及其参数。不知道更多有关你要完成什么,我无法给出更具体的建议,但总的来说,我建议 protlib 一>库,因为它是我用C和Python程序之间的通信(声明:我是protlib的作者)。
I recommend creating a Command
struct with fields and codes to represent commands and their arguments. I can't give much more specific advice without knowing more about what you want to accomplish, but in general I recommend the protlib library, since it's what I use to communicate between C and Python programs (disclaimer: I am the author of protlib).
这篇关于你如何调用从C code的Python code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!