1

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 3

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

i still cant get a = 1 working :( PyObject and PyIntObject are not letting me do anything
The question suggests he is interested in embedding Python into C++ rather than extending Python with C/C++ code
Extending and Embedding are both contained in the main doc (first link about).
2

I 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

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.