任何人都可以给我看一个基本的程序,其中包括在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