当前位置:首页 » 编程语言 » boost调用python

boost调用python

发布时间: 2023-06-05 20:23:37

㈠ 如何实现 C/C++ 与 python 的通信

属于混合编程的问题。较全面的介绍一下,不仅限于题主提出的问题。
以下讨论中,Python指它的标准实现,即CPython(虽然不是很严格)

本文分4个部分

C/C++ 调用 Python (基础篇)— 仅讨论Python官方提供的实现方式
Python 调用 C/C++ (基础篇)— 仅讨论Python官方提供的实现方式
C/C++ 调用 Python (高级篇)— 使用 Cython
Python 调用 C/C++ (高级篇)— 使用 SWIG

练习本文中的例子,需要搭建Python扩展开发环境。具体细节见搭建Python扩展开发环境 - 蛇之魅惑 - 知乎专栏

1 C/C++ 调用 Python(基础篇)
Python 本身就是一个C库。你所看到的可执行体python只不过是个stub。真正的python实体在动态链接库里实现,在Windows平台上,这个文件位于 %SystemRoot%\System32\python27.dll。

你也可以在自己的程序中调用Python,看起来非常容易:

//my_python.c
#include <Python.h>

int main(int argc, char *argv[])
{
Py_SetProgramName(argv[0]);
Py_Initialize();
PyRun_SimpleString("print 'Hello Python!'\n");
Py_Finalize();
return 0;
}

在Windows平台下,打开Visual Studio命令提示符,编译命令为
cl my_python.c -IC:\Python27\include C:\Python27\libs\python27.lib

linux下编译命令为
gcc my_python.c -o my_python -I/usr/include/python2.7/ -lpython2.7

在Mac OS X 下的编译命令同上

产生可执行文件后,直接运行,结果为输出
Hello Python!

Python库函数PyRun_SimpleString可以执行字符串形式的Python代码。

虽然非常简单,但这段代码除了能用C语言动态生成一些Python代码之外,并没有什么用处。我们需要的是C语言的数据结构能够和Python交互。

下面举个例子,比如说,有一天我们用Python写了一个功能特别强大的函数:

def great_function(a):
return a + 1

接下来要把它包装成C语言的函数。我们期待的C语言的对应函数应该是这样的:

int great_function_from_python(int a) {
int res;
// some magic
return res;
}

首先,复用Python模块得做‘import’,这里也不例外。所以我们把great_function放到一个mole里,比如说,这个mole名字叫 great_mole.py

接下来就要用C来调用Python了,完整的代码如下:
#include <Python.h>

int great_function_from_python(int a) {
int res;
PyObject *pMole,*pFunc;
PyObject *pArgs, *pValue;

/* import */
pMole = PyImport_Import(PyString_FromString("great_mole"));

/* great_mole.great_function */
pFunc = PyObject_GetAttrString(pMole, "great_function");

/* build args */
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0, PyInt_FromLong(a));

/* call */
pValue = PyObject_CallObject(pFunc, pArgs);

res = PyInt_AsLong(pValue);
return res;
}

从上述代码可以窥见Python内部运行的方式:

所有Python元素,mole、function、tuple、string等等,实际上都是PyObject。C语言里操纵它们,一律使用PyObject *。
Python的类型与C语言类型可以相互转换。Python类型XXX转换为C语言类型YYY要使用PyXXX_AsYYY函数;C类型YYY转换为Python类型XXX要使用PyXXX_FromYYY函数。
也可以创建Python类型的变量,使用PyXXX_New可以创建类型为XXX的变量。
若a是Tuple,则a[i] = b对应于 PyTuple_SetItem(a,i,b),有理由相信还有一个函数PyTuple_GetItem完成取得某一项的值。
不仅Python语言很优雅,Python的库函数API也非常优雅。

现在我们得到了一个C语言的函数了,可以写一个main测试它
#include <Python.h>

int great_function_from_python(int a);

int main(int argc, char *argv[]) {
Py_Initialize();
printf("%d",great_function_from_python(2));
Py_Finalize();
}

编译的方式就用本节开头使用的方法。
在Linux/Mac OSX运行此示例之前,可能先需要设置环境变量:
bash:
export PYTHONPATH=.:$PYTHONPATH

csh:
setenv PYTHONPATH .:$PYTHONPATH

2 Python 调用 C/C++(基础篇)
这种做法称为Python扩展。
比如说,我们有一个功能强大的C函数:
int great_function(int a) {
return a + 1;
}

期望在Python里这样使用:
>>> from great_mole import great_function
>>> great_function(2)
3

考虑最简单的情况。我们把功能强大的函数放入C文件 great_mole.c 中。
#include <Python.h>

int great_function(int a) {
return a + 1;
}

static PyObject * _great_function(PyObject *self, PyObject *args)
{
int _a;
int res;

if (!PyArg_ParseTuple(args, "i", &_a))
return NULL;
res = great_function(_a);
return PyLong_FromLong(res);
}

static PyMethodDef GreateMoleMethods[] = {
{
"great_function",
_great_function,
METH_VARARGS,
""
},
{NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initgreat_mole(void) {
(void) Py_InitMole("great_mole", GreateMoleMethods);
}

除了功能强大的函数great_function外,这个文件中还有以下部分:

包裹函数_great_function。它负责将Python的参数转化为C的参数(PyArg_ParseTuple),调用实际的great_function,并处理great_function的返回值,最终返回给Python环境。

出表GreateMoleMethods。它负责告诉Python这个模块里有哪些函数可以被Python调用。导出表的名字可以随便起,每一项有4
个参数:第一个参数是提供给Python环境的函数名称,第二个参数是_great_function,即包裹函数。第三个参数的含义是参数变长,第四个
参数是一个说明性的字符串。导出表总是以{NULL, NULL, 0, NULL}结束。
导出函数initgreat_mole。这个的名字不是任取的,是你的mole名称添加前缀init。导出函数中将模块名称与导出表进行连接。

在Windows下面,在Visual Studio命令提示符下编译这个文件的命令是
cl /LD great_mole.c /o great_mole.pyd -IC:\Python27\include C:\Python27\libs\python27.lib

/LD 即生成动态链接库。编译成功后在当前目录可以得到 great_mole.pyd(实际上是dll)。这个pyd可以在Python环境下直接当作mole使用。

在Linux下面,则用gcc编译:
gcc -fPIC -shared great_mole.c -o great_mole.so -I/usr/include/python2.7/ -lpython2.7

在当前目录下得到great_mole.so,同理可以在Python中直接使用。

本部分参考资料

《Python源码剖析-深度探索动态语言核心技术》是系统介绍CPython实现以及运行原理的优秀教程。
Python 官方文档的这一章详细介绍了C/C++与Python的双向互动Extending and Embedding the Python Interpreter
关于编译环境,本文所述方法仅为出示原理所用。规范的方式如下:3. Building C and C++ Extensions with distutils
作为字典使用的官方参考文档 Python/C API Reference Manual

用以上的方法实现C/C++与Python的混合编程,需要对Python的内部实现有相当的了解。接下来介绍当前较为成熟的技术Cython和SWIG。

3 C/C++ 调用 Python(使用Cython)


前面的小节中谈到,Python的数据类型和C的数据类型貌似是有某种“一一对应”的关系的,此外,由于Python(确切的说是CPython)本身是
由C语言实现的,故Python数据类型之间的函数运算也必然与C语言有对应关系。那么,有没有可能“自动”的做替换,把Python代码直接变成C代码
呢?答案是肯定的,这就是Cython主要解决的问题。

安装Cython非常简单。Python 2.7.9以上的版本已经自带easy_install:
easy_install -U cython

在Windows环境下依然需要Visual
Studio,由于安装的过程需要编译Cython的源代码,故上述命令需要在Visual
Studio命令提示符下完成。一会儿使用Cython的时候,也需要在Visual
Studio命令提示符下进行操作,这一点和第一部分的要求是一样的。

继续以例子说明:
#great_mole.pyx
cdef public great_function(a,index):
return a[index]

这其中有非Python关键字cdef和public。这些关键字属于Cython。由于我们需要在C语言中使用
“编译好的Python代码”,所以得让great_function从外面变得可见,方法就是以“public”修饰。而cdef类似于Python的
def,只有使用cdef才可以使用Cython的关键字public。

这个函数中其他的部分与正常的Python代码是一样的。

接下来编译 great_mole.pyx
cython great_mole.pyx

得到great_mole.h和great_mole.c。打开great_mole.h可以找到这样一句声明:
__PYX_EXTERN_C DL_IMPORT(PyObject) *great_function(PyObject *, PyObject *)

写一个main使用great_function。注意great_function并不规定a是何种类型,它的
功能只是提取a的第index的成员而已,故使用great_function的时候,a可以传入Python
String,也可以传入tuple之类的其他可迭代类型。仍然使用之前提到的类型转换函数PyXXX_FromYYY和PyXXX_AsYYY。

//main.c
#include <Python.h>
#include "great_mole.h"

int main(int argc, char *argv[]) {
PyObject *tuple;
Py_Initialize();
initgreat_mole();
printf("%s\n",PyString_AsString(
great_function(
PyString_FromString("hello"),
PyInt_FromLong(1)
)
));
tuple = Py_BuildValue("(iis)", 1, 2, "three");
printf("%d\n",PyInt_AsLong(
great_function(
tuple,
PyInt_FromLong(1)
)
));
printf("%s\n",PyString_AsString(
great_function(
tuple,
PyInt_FromLong(2)
)
));
Py_Finalize();
}

编译命令和第一部分相同:
在Windows下编译命令为
cl main.c great_mole.c -IC:\Python27\include C:\Python27\libs\python27.lib

在Linux下编译命令为
gcc main.c great_mole.c -o main -I/usr/include/python2.7/ -lpython2.7

这个例子中我们使用了Python的动态类型特性。如果你想指定类型,可以利用Cython的静态类型关键字。例子如下:

#great_mole.pyx
cdef public char great_function(const char * a,int index):
return a[index]

cython编译后得到的.h里,great_function的声明是这样的:
__PYX_EXTERN_C DL_IMPORT(char) great_function(char const *, int);

很开心对不对!
这样的话,我们的main函数已经几乎看不到Python的痕迹了:
//main.c
#include <Python.h>
#include "great_mole.h"

int main(int argc, char *argv[]) {
Py_Initialize();
initgreat_mole();
printf("%c",great_function("Hello",2));
Py_Finalize();
}

在这一部分的最后我们给一个看似实用的应用(仅限于Windows):
还是利用刚才的great_mole.pyx,准备一个dllmain.c:
#include <Python.h>
#include <Windows.h>
#include "great_mole.h"

extern __declspec(dllexport) int __stdcall _great_function(const char * a, int b) {
return great_function(a,b);
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpReserved) {
switch( fdwReason ) {
case DLL_PROCESS_ATTACH:
Py_Initialize();
initgreat_mole();
break;
case DLL_PROCESS_DETACH:
Py_Finalize();
break;
}
return TRUE;
}

在Visual Studio命令提示符下编译:
cl /LD dllmain.c great_mole.c -IC:\Python27\include C:\Python27\libs\python27.lib

会得到一个dllmain.dll。我们在Excel里面使用它,没错,传说中的Excel与Python混合编程:

参考资料:Cython的官方文档,质量非常高:
Welcome to Cython’s Documentation

出自:Jerry Jho

㈡ boost.python 库,在 VC 中如何选择

1、查看boost编译是否已经生成boost_python-vc120-mt-gd-1_58.lib。注意python与boost是32位或64位版本,版本要对应。


我之前因为boost编译是的64位,而python是32位的,造成链接失败。可以使用mpbin /headers xxx.dll检查是32位还是64位。

仅供参考。

㈢ 在linux系统下,安装boost.python库时问题求解

你把这个mole 重新安装在python目录下,或者在path里把mole所在目录添加上。。。

㈣ VS2013 boost.python 编译错误,请教一下

  1. 确认文件boost/python.hpp存在

  2. #include包含语句,应该放在源文件首部,其它代码之前(其它#include之后)

  3. 尝试增加作用域定义:

using namespace boost::python;

㈤ 如何实现 C/C++ 与 Python 的通信

这个事情做过好多遍,摸索的过程基本这样的:
1. 通过stdout通信...土到爆,但上手极快,简单粗暴;
2. 调用原始的python.h 接口,编写可以被python import 的so,支持python调用c++接口,c++接口调用python同样的方式;
3. 使用boost-python 完成2中的功能,接口简单很多,本质上没有不同;

这里遇到的主要几个问题在于:
1. 数据的序列化反序列化,因为有时c++和python之间通信的不是基本类型,可能是用户自定义类型;
2. 多线程的问题,c++多线程调python接口时,需要注意GIL的使用,貌似因为python解释器不是线程安全的;
3.

对象传递,大多数情况下,如果只是静态接口调用,都比较简单,考虑一种情况:c++中的对象的一个函数调用python一个接口,这个python接口中
又需要反过来调用这个对象中的另一个接口,这里就需要考虑怎么把对象相互传递,我这里是把对象指针地址传递到python中,在python中调用一个
c++的静态接口,带上地址和其他需要的参数,在这个c++的静态接口中,把地址转换成指针在调用..

㈥ python调用c函数

Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过
1. Python 调用 C (base)
想在python中调用c函数, 如这儿的fact
#include <Python.h>

int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}

PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;

if (! PyArg_ParseTuple(args, "i:fact", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}

static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};

void initexample()
{
PyObject* m;
m = Py_InitMole("example", exampleMethods);
}

把这段代码存为wrapper.c, 编成so库,
gcc -fPIC wrapper.c -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

然后在有此so库的目录, 进入python, 可以如下使用
import example
example.fact(4)

2. Python 调用 C++ (base)
在python中调用C++类成员函数, 如下调用TestFact类中的fact函数,
#include <Python.h>

class TestFact{
public:
TestFact(){};
~TestFact(){};
int fact(int n);
};

int TestFact::fact(int n)
{
if (n <= 1)
return 1;
else
return n * (n - 1);
}

int fact(int n)
{
TestFact t;
return t.fact(n);
}
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;

if (! PyArg_ParseTuple(args, "i:fact", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}

static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};

extern "C" //不加会导致找不到initexample
void initexample()
{
PyObject* m;
m = Py_InitMole("example", exampleMethods);
}

把这段代码存为wrapper.cpp, 编成so库,
g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

然后在有此so库的目录, 进入python, 可以如下使用
import example
example.fact(4)

3. Python 调用 C++ (Boost.Python)
Boost库是非常强大的库, 其中的python库可以用来封装c++被python调用, 功能比较强大, 不但可以封装函数还能封装类, 类成员.
http://dev.gameres.com/Program/Abstract/Building%20Hybrid%20Systems%20with%20Boost_Python.CHN.by.JERRY.htm
首先在ubuntu下安装boost.python, apt-get install libboost-python-dev
#include <boost/python.hpp>
char const* greet()
{
return "hello, world";
}

BOOST_PYTHON_MODULE(hello)
{
using namespace boost::python;
def("greet", greet);
}

把代码存为hello.cpp, 编译成so库
g++ hello.cpp -o hello.so -shared -I/usr/include/python2.5 -I/usr/lib/python2.5/config -lboost_python-gcc42-mt-1_34_1

此处python路径设为你的python路径, 并且必须加-lboost_python-gcc42-mt-1_34_1, 这个库名不一定是这个, 去/user/lib查

然后在有此so库的目录, 进入python, 可以如下使用
>>> import hello
>>> hello.greet()
'hello, world'

4. python 调用 c++ (ctypes)
ctypes is an advanced ffi (Foreign Function Interface) package for Python 2.3 and higher. In Python 2.5 it is already included.
ctypes allows to call functions in dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python.
http://python.net/crew/theller/ctypes/

#include <Python.h>

class TestFact{
public:
TestFact(){};
~TestFact(){};
int fact(int n);
};

int TestFact::fact(int n)
{
if (n <= 1)
return 1;
else
return n * (n - 1);
}

extern "C"
int fact(int n)
{
TestFact t;
return t.fact(n);
}
将代码存为wrapper.cpp不用写python接口封装, 直接编译成so库,
g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

进入python, 可以如下使用
>>> import ctypes
>>> pdll = ctypes.CDLL('/home/ubuntu/tmp/example.so')
>>> pdll.fact(4)
12

热点内容
邮政登陆密码是什么意思 发布:2025-07-15 01:53:23 浏览:229
算法与程序设计vb 发布:2025-07-15 01:50:39 浏览:719
什么是测试脚本 发布:2025-07-15 01:44:58 浏览:514
商汤科技存储负责人 发布:2025-07-15 01:24:21 浏览:252
文件夹如何批量替换文件名 发布:2025-07-15 01:19:15 浏览:68
ftp上传网页 发布:2025-07-15 01:13:09 浏览:182
音乐文件夹图标 发布:2025-07-15 01:03:41 浏览:495
安卓机怎么反向充电 发布:2025-07-15 01:03:40 浏览:501
电脑使用华为云服务器 发布:2025-07-15 00:48:10 浏览:534
中考应该如何排解压力 发布:2025-07-15 00:17:54 浏览:363