Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_33_1/libs/python/test/embedding.cpp @ 12

Last change on this file since 12 was 12, checked in by landauf, 17 years ago

added boost

File size: 4.8 KB
Line 
1// Copyright David Abrahams 2002.
2// Distributed under the Boost Software License, Version 1.0. (See
3// accompanying file LICENSE_1_0.txt or copy at
4// http://www.boost.org/LICENSE_1_0.txt)
5
6// embedded_hello -- A simple Boost.Python embedding example -- by
7// Dirk Gerrits
8
9#include <boost/python.hpp>
10#include <boost/scoped_ptr.hpp>
11#include <iostream>
12#include <stdexcept>
13#include <cassert>
14
15namespace python = boost::python;
16
17// An abstract base class
18class Base : public boost::noncopyable
19{
20public:
21    virtual ~Base() {};
22
23    virtual std::string hello() = 0;
24};
25
26// C++ derived class
27class CppDerived : public Base
28{
29public:
30    virtual ~CppDerived() {}
31
32    std::string hello()
33    {
34        return "Hello from C++!";
35    }
36};
37
38// Familiar Boost.Python wrapper class for Base
39struct BaseWrap : public Base
40{
41    BaseWrap(PyObject* self_)
42        : self(self_) {}
43
44    std::string hello() { return python::call_method<std::string>(self, "hello"); }
45
46    PyObject* self;
47};
48
49// Pack the Base class wrapper into a module
50BOOST_PYTHON_MODULE(embedded_hello)
51{
52    python::class_<Base, BaseWrap, boost::noncopyable>("Base")
53        ;
54
55}
56
57
58void test()
59{
60//- INITIALIZATION -----------------------------------------------------------//
61
62    // Register the module with the interpreter
63    if (PyImport_AppendInittab("embedded_hello", initembedded_hello) == -1)
64        throw std::runtime_error("Failed to add embedded_hello to the interpreter's "
65                                 "builtin modules");
66    // Retrieve the main module
67    python::object main_module((
68        python::handle<>(python::borrowed(PyImport_AddModule("__main__")))));
69
70    // Retrieve the main module's namespace
71    python::object main_namespace((main_module.attr("__dict__")));
72
73    // Define the derived class in Python.
74    // (You'll normally want to put this in a .py file.)
75    python::handle<> result(
76        PyRun_String(
77        "from embedded_hello import *        \n"
78        "class PythonDerived(Base):          \n"
79        "    def hello(self):                \n"
80        "        return 'Hello from Python!' \n",
81        Py_file_input, main_namespace.ptr(), main_namespace.ptr())
82        );
83    // Result is not needed
84    result.reset();
85
86    // Extract the raw Python object representing the just defined derived class
87    python::handle<> class_ptr(
88        PyRun_String("PythonDerived\n", Py_eval_input,
89                     main_namespace.ptr(), main_namespace.ptr()) );
90
91    // Wrap the raw Python object in a Boost.Python object
92    python::object PythonDerived(class_ptr);
93
94//- MAIN PROGRAM -------------------------------------------------------------//
95
96    // Creating and using instances of the C++ class is as easy as always.
97    CppDerived cpp;
98    std::cout << cpp.hello() << std::endl;
99
100    // But now creating and using instances of the Python class is almost
101    // as easy!
102    python::object py_base = PythonDerived();
103    Base& py = python::extract<Base&>(py_base)
104#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) || BOOST_WORKAROUND(BOOST_INTEL_WIN, <= 900)
105        ()
106#endif
107        ;
108    std::cout << py.hello() << std::endl;
109}
110
111void
112test_tutorial()
113{
114    using namespace boost::python;
115
116    object main_module((
117        handle<>(borrowed(PyImport_AddModule("__main__")))));
118
119    object main_namespace = main_module.attr("__dict__");
120
121    handle<> ignored((PyRun_String(
122
123        "hello = file('hello.txt', 'w')\n"
124        "hello.write('Hello world!')\n"
125        "hello.close()"
126
127      , Py_file_input
128      , main_namespace.ptr()
129      , main_namespace.ptr())
130    ));
131}
132
133void
134test_tutorial2()
135{
136    using namespace boost::python;
137
138    object main_module((
139         handle<>(borrowed(PyImport_AddModule("__main__")))));
140
141    object main_namespace = main_module.attr("__dict__");
142
143    handle<> ignored((PyRun_String(
144
145        "result = 5 ** 2"
146
147        , Py_file_input
148        , main_namespace.ptr()
149        , main_namespace.ptr())
150    ));
151
152    int five_squared = extract<int>(main_namespace["result"]);
153    assert(five_squared == 25);
154
155    object result((handle<>(
156        PyRun_String("5 ** 2"
157            , Py_eval_input
158            , main_namespace.ptr()
159            , main_namespace.ptr()))
160    ));
161
162    int five_squared2 = extract<int>(result);
163    assert(five_squared2 == 25);
164}
165
166int main()
167{
168    // Initialize the interpreter
169    Py_Initialize();
170
171    if (python::handle_exception(test))
172    {
173        if (PyErr_Occurred())
174            PyErr_Print();
175        return 1;
176    }
177
178    if (python::handle_exception(test_tutorial))
179    {
180        if (PyErr_Occurred())
181            PyErr_Print();
182        return 1;
183    }
184
185    if (python::handle_exception(test_tutorial2))
186    {
187        if (PyErr_Occurred())
188            PyErr_Print();
189        return 1;
190    }
191
192    // Boost.Python doesn't support Py_Finalize yet.
193    // Py_Finalize();
194    return 0;
195}
196#include "module_tail.cpp"
Note: See TracBrowser for help on using the repository browser.