can anyone show me a basic program that includes python in a c++ program? i have gotten #include <Python.h> to work, but thats about it. how do you create a string, int, and include a module that is not part of the python library?
3 Answers
Maybe the main Python doc can help here: http://docs.python.org/extending/
Here's a simple module written in C: http://docs.python.org/extending/extending.html#a-simple-example
3 Comments
a = 1 working :( PyObject and PyIntObject are not letting me do anythingI suggest Boost Python, since you're using C++ rather than C. The documentation is decent, but note that you can skip much of the "Hello World" example if your platform has Boost packages already built for it (so you don't need to build Boost yourself using bjam).
Comments
Definitely use Boost Python. It is a lightweight dependency (doesn't require changes to existing C++ code), though it does increase compile times slightly.
You can install boost python on ubuntu (or the pkg manager for your platform):
$ sudo apt-get install boost-python
Then a simple library looks like this:
#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);
}
Then compile with
$ g++ -shared mymodule.cpp -I/usr/include/python -lboost_python -omymodule.so
Finally, import and use it in python
>>> import mymodule
>>> mymodule.myfunction(5)
6
>>> s = mymodule.mystruct()
>>> s.value = 4
>>> s.value
4