从C调用Python [英] calling Python from C

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

问题描述

我有一个C代码,出于初始化目的,一开始我需要做一些简单的文件操作,而使用Python则很简单。我想知道是否有一种方法可以通过C调用python。我熟悉从Python调用C,但是相反,我已经读过Cython可以做到的事情,但是我对如何做感到很困惑。

Python代码必须输入一些字符串,进行一些文件操作并返回一些双精度和数组。

解决方案

要从C调用Python,这非常简单。首先,您需要安装python-dev软件包才能访问Python.h文件。那么您就可以访问python api。这是api的参考: https://docs.python.org/2 /c-api/intro.html 。请特别注意嵌入式Python部分。基本过程是调用Py_Initialize()执行您的python代码,然后调用Py_Finalize()


I have an C code, and there is some simple file manipulation I would need to do at the beginning for initialization purposes, that would be straightforward with Python. I was wondering if there is a way to do that with calling python from C. I am familiar with calling C from Python, but for doing the opposite I have read that Cython could do but I am very confused on how.

The python code has to take in input some strings, make some files manipulation and return some doubles and arrays.

解决方案

To call Python from C, it is quite simple. First you need to install the python-dev packages to get access to the Python.h file. then you have access to the python api. Here is the reference for the api: https://docs.python.org/2/c-api/intro.html. specifically pay attention to the Embedding Python section. The basic process is to call Py_Initialize() execute your python code and then call Py_Finalize()

这篇关于从C调用Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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