1 - c_call_Python api

来源:互联网 发布:js点击按钮打开新窗口 编辑:程序博客网 时间:2024/05/17 09:06

C语言调用Python

Py_Initialize()

void Py_Initialize(void);

初始化Python虚拟机。

/*初始化Python  在使用Python系统前,必须使用Py_Initialize对其进行初始化。它会载入Python的内建模块并添加系统路径到模块搜索路径中。这个函数没有返回值检查系统是否初始化成功需要使用Py_IsInitialized.*/Py_Initialize();if (!Py_IsInitialized()){  return -1;}

Py_IsInitialized()

int Py_IsInitialized(void);

检查Python虚拟机是否成功初始化,成功返回1,失败返回0。

Py_Finalize()

void Py_Finalize(void);

关闭Python虚拟机,与Py_Initialize()配对使用。

PyRun_SimpleString()

#define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL);

int PyRun_SimpleStringFlags(const char *, PyCompilerFlags *);

Returns 0 on success or -1 if an exception was raised.

该函数无法在Python和C之间传递信息,只是执行Python语句,以前执行的语句对后面的语句是有效的,相当于在同一个交互式命令行中顺序执行语句。

PyRun_SimpleString("print 'import os'"); //打印import osPyRun_SimpleString("import os");         //执行import os,等同于在Python中执行import osPyRun_SimpleString("print os.getcwd()"); //打印当前工作路径PyRun_SimpleString("x = 10");PyRun_SimpleString("y = 10");PyRun_SimpleString("print x + y");       //打印结果为20

PyRun_SimpleString将所有的代码都放在 __main__ 模块中运行。

PyRun_String()

#define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL);

PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals);

PyRun_SimpleString的升级版,可以传递参数。

example.

#include "python.h" #include <stdio.h>int  main(int  argc, char * argv[]){    int result = 0;    PyObject* mainModule;    PyObject* dict;    PyObject* result_python    Py_Initialize();    PyRun_SimpleString("x = 10" );    PyRun_SimpleString("y = 20" );    PyObject* mainModule = PyImport_ImportModule("__main__" ); //倒入__main__模块    PyRun_SimpleString("print globals()");    PyObject* dict = PyModule_GetDict(mainModule);             //获取__main__模块的dict    PyObject* result_python = PyRun_String("x + y" , Py_eval_input, dict, dict);    if (result_python)    {        result = PyLong_AsLong(result_python);        printf(" %d " , result);    }    Py_Finalize();    system("PAUSE" );    return  0 ;}

PyImport_ImportModule()

PyObject *) PyImport_ImportModule(const char *filename);

导入一个Python模块,参数filename是*.py文件的文件名。类似Python内建函数import。

PyImport_ImportModule("hello");  //导入hello.py

PyEval_CallObject()

define PyEval_CallObject(func,arg) PyEval_CallObjectWithKeywords(func, args, (PyObject *)NULL);

PyObject * PyEval_CallObjectWithKeywords(PyObject *, PyObject *, PyObject *);

pfunc是要调用的Python 函数,一般说来可以使用PyObject_GetAttrString()获得,args是函数的参数列表,通常是使用Py_BuildValue()构建。

以上三个函数共同使用

PyObject* pmoudle = NULL;PyObject* pfunc = NULL;pmoudle = PyImport_ImportModule("hello");  //导入hello.pyif (!pmoudle){    printf("import module error");    return 0;}pfunc = PyObject_GetAttrString(pmoudle, "func");if (!pfunc){    printf("can not find func");    return 0;}PyEval_CallObject(pfunc, NULL);

PyObject_CallObject()

调用Python中的函数

PyObject * PyObject_CallObject(PyObject *callable_object, PyObject *args);   /*Call a callable Python object, callable_object, with arguments given by the tuple, args.  If no arguments are needed, then args may be NULL.  Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: apply(o,args).*/

Py_BuildValue()

PyObject * Py_BuildValue(const char *, ...);

和PyArg_Parse刚好相反,构建一个参数列表,把C类型转换为Python对象,使得Python里面可以使用C类型数据。参数列表中的个数要与参数个数相同。

s 表示字符串,i表示整型变量,f表示浮点数,o表示一个Python对象

PyObject *pArg = NULL;pArg = Py_BuildValue("(s,s)", "hello_python","123456");  //括号必须写,代表元组,s代表字符串类型,函数传参使用

PyArg_Parse()

int PyArg_Parse(PyObject *, const char *, ...);

将python类型的返回值转换为c/c++类型,转换成功返回1,失败返回0。

s 表示字符串,i表示整型变量,f表示浮点数,o表示一个Python对象

PyArg_Parse(var_python, "i", &var_c);

PyArg_ParseTuple()

int PyArg_ParseTuple(PyObject * tuple_name, const char * format, …)

解析Python的元组,貌似必须将元组中的元素全部解析,局部无法解析。使用参考

s 表示字符串,i表示整型变量,f表示浮点数,o表示一个Python对象

解析格式不能简写,如解析5个整数,需要写成”iiiii”,不能写成”5i”。

example

Tuple = (1,2,3,4,5)    //C中的Python变量PyArg_ParseTuple(Tuple,"iiiii",&a,&b,&c,&d,&e) //后面的参数要与解释个数相同,而且不能使用二维指针,只能一个参数yield参数的写...

PyModule_GetDict()

PyObject * PyModule_GetDict(PyObject *modulename);

相当于Python模块对象的__dict__属性,得到模块名称空间下的字典对象。

PyDict_GetItemString()

PyObject * PyDict_GetItemString(PyObject *module_dict, const char *key);

获取字典中key->value

PyObject_GetAttrString()

PyObject * PyObject_GetAttrString(PyObject *o, const char *attr_name);

返回模块对象o中的attr_name 属性或函数,相当于Python中表达式语句,o.attr_name。

PyInstance_New()

PyInstance_New(PyObject *classname, PyObject *, PyObject *);

实例化类

PyObject_CallMethod()

PyAPI_FUNC(PyObject *) PyObject_CallMethod(PyObject *o, char *m,char *format, ...);/*Call the method named m of object o with a variable number of C arguments.  The C arguments are described by a mkvalue format string. The format may be NULL, indicating that noarguments are provided. Returns the result of the call on success, or NULL on failure.  This is the equivalent of the Python expression: o.method(args).*/

调用实例的方法

PyString_AsString()

char * PyString_AsString(PyObject * str);

将Python中的字符串类型转换为C中字符串类型,用于操作函数返回值

PyInt_AsLong()

long PyInt_AsLong(PyObject *);

将Python中的long->C中的long。

PyTuple_New

PyObject * PyTuple_New(Py_ssize_t size);

生成元组

PyTuple_SetItem

int PyTuple_SetItem(PyObject * tuple_name, index, PyObject * val);

tuple_name[index] = val

PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));

转载请标明出处,原文地址(http://blog.csdn.net/lis_12/article/details/53966091).

如果觉得本文对您有帮助,请点击‘顶’支持一下,您的支持是我写作最大的动力,谢谢。

参考链接

  1. http://www.2cto.com/kf/201411/352264.html
  2. http://www.cnblogs.com/linxr/archive/2011/07/22/2113843.html
0 0
原创粉丝点击