任何人都可以給我看一個基本的程序,其中包括在c + +程序中的Python?我已經得到#include <Python.h>
工作,但那是關於它。你如何創建一個字符串,int,幷包含一個不屬於python庫的模塊?在C++基礎知識中使用python
1
A
回答
3
也許主要的Python文檔可以幫助在這裏:http://docs.python.org/extending/
下面是用C語言編寫一個簡單的模塊:http://docs.python.org/extending/extending.html#a-simple-example
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
相關問題
- 1. C++基礎知識
- 2. 使用Python鼻子的基礎知識
- 3. Python和Django基礎知識
- 4. C#和sqlite基礎知識
- 5. kinect基礎知識和C#
- 6. Asp.net c# - MVC基礎知識
- 7. C++模板 - 基礎知識
- 8. Python中空列表的基礎知識
- 9. Threading基礎知識
- 10. Ruby基礎知識
- 11. 基礎SQL知識?
- 12. Modernizr基礎知識
- 13. Feedburner基礎知識
- 14. AOP基礎知識
- 15. Makefile基礎知識
- 16. SceneKit基礎知識
- 17. Python程序包基礎知識
- 18. 使用Crashlog調試iOS(基礎知識)
- 19. 使用Microsoft Async Framework的基礎知識
- 20. C++封裝的基礎知識
- 21. C++,關於繼承的基礎知識
- 22. Objective-C,iPhone SDK基礎知識
- 23. Spring Security基礎知識
- 24. XML到WordML基礎知識
- 25. Atom feed基礎知識
- 26. 新手Git基礎知識
- 27. Java開關基礎知識
- 28. codeIgniter導航基礎知識
- 29. BlackBerry VerticalFieldManager基礎知識
- 30. TCP連接基礎知識
我仍然不能讓'a = 1'工作:(PyObject和PyIntObject不讓我做任何事情 – calccrypto 2011-05-17 02:29:57
這個問題表明他有興趣*將Python嵌入到C++而不是擴展Python用C/C++代碼 – 2011-05-17 04:26:08
擴展和嵌入都包含在主文檔(第一個鏈接)。 – 2011-05-17 07:23:11