如何从C代码调用Python代码? [英] How do you call Python code from C code?

查看:624
本文介绍了如何从C代码调用Python代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展一个大型的C项目有一些新的功能,但我真的想写它在Python。基本上,我想从C代码调用Python代码。但是,像SWIG这样的Python-> C包装器允许使用OPPOSITE,即编写C模块和从Python调用C。



我正在考虑使用IPC或RPC (我不介意有多个进程);也就是说,让我的纯Python组件在一个单独的进程(在同一台机器上)运行,并让我的C项目通过从套接字(或unix管道)写/读来与它通信。我的python组件可以读/写socket以进行通信。这是一个合理的方法吗?有更好的东西吗?像一些特殊的RPC机制?



感谢您的答案 - 然而,我想关注基于IPC的方法,因为我想有我的Python程序在一个单独的进程中作为我的C程序。我不想嵌入一个Python解释器。感谢!

解决方案

我推荐这里详述的方法。它首先解释如何执行Python代码字符串,然后从那里详细说明如何设置一个Python环境与C程序交互,从C代码调用Python函数,从C代码处理Python对象等。 p>

EDIT :如果你真的想去IPC的路由,那么你需要使用 struct模块或更好, protlib 。 Python和C进程之间的大多数通信都围绕着来回传递结构,或者通过套接字< a>或通过共享内存



我建议用字段和代码创建一个命令结构来表示命令及其参数。我不能提供更多具体的建议,但不知道更多关于你想要完成什么,但一般来说,我建议 protlib 库,因为它是我用来在C和Python程序之间通信的(免责声明:我是protlib的作者)。


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.

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?

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!

解决方案

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.

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.

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代码调用Python代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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