2011-05-17 104 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