2011-05-17 101 views
1

任何人都可以给我看一个基本的程序,其中包括在c + +程序中的Python?我已经得到#include <Python.h>工作,但那是关于它。你如何创建一个字符串,int,并包含一个不属于python库的模块?在C++基础知识中使用python

回答

3

也许主要的Python文档可以帮助在这里:http://docs.python.org/extending/

下面是用C语言编写一个简单的模块:http://docs.python.org/extending/extending.html#a-simple-example

+0

我仍然不能让'a = 1'工作:(PyObject和PyIntObject不让我做任何事情 – calccrypto 2011-05-17 02:29:57

+0

这个问题表明他有兴趣*将Python嵌入到C++而不是扩展Python用C/C++代码 – 2011-05-17 04:26:08

+0

扩展和嵌入都包含在主文档(第一个链接)。 – 2011-05-17 07:23:11

2

我建议Boost Python,因为你正在使用C++而不是C.文档是体面的,但是请注意,如果您的平台已经为其构建了Boost包,那么您可以跳过大部分“Hello World”示例(因此您不需要使用bjam自行构建Boost)。

1

绝对使用Boost Python。它是一个轻量级的依赖项(不需要修改现有的C++代码),尽管它稍微增加了编译时间。

可以安装在Ubuntu升压蟒蛇(或用平台的PKG经理):

$ sudo apt-get install boost-python 

然后一个简单的库看起来是这样的:

#include <boost/python.hpp> 

using namespace boost::python; 

struct mystruct { 
    int value; 
} 

int myfunction(int i) { 
    return i + 1; 
} 

BOOST_PYTHON_MODULE(mymodule) { 
    // Code placed here will be executed when you do "import mymodule" in python 
    initialize_my_module(); 

    // Declare my C++ data structures 
    class_<mystruct>("mystruct") 
     .def_readwrite("value", &mystruct::value) 
     ; 

    // Declare my C++ functions 
    def("myfunction", myfunction); 
} 

然后用

$ g++ -shared mymodule.cpp -I/usr/include/python -lboost_python -omymodule.so 
编译

最后,在python中导入并使用它

>>> import mymodule 
>>> mymodule.myfunction(5) 
6 
>>> s = mymodule.mystruct() 
>>> s.value = 4 
>>> s.value 
4