1 | // Copyright Stefan Seefeld 2007. |
---|
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 | #include <boost/python.hpp> |
---|
7 | #include <boost/bind.hpp> |
---|
8 | #include <boost/detail/lightweight_test.hpp> |
---|
9 | #include <iostream> |
---|
10 | #include <sstream> |
---|
11 | |
---|
12 | namespace bpl = boost::python; |
---|
13 | |
---|
14 | void import_test( char** argv ) |
---|
15 | { |
---|
16 | // Retrieve the main module |
---|
17 | bpl::object main = bpl::import("__main__"); |
---|
18 | |
---|
19 | // Retrieve the main module's namespace |
---|
20 | bpl::object global(main.attr("__dict__")); |
---|
21 | |
---|
22 | // Inject search path for import_ module |
---|
23 | std::ostringstream script; |
---|
24 | script << "import sys, os\n" |
---|
25 | << "path = os.path.dirname('" << argv[1] << "')\n" |
---|
26 | << "sys.path.insert(0, path)\n"; |
---|
27 | bpl::exec(bpl::str(script.str()), global, global); |
---|
28 | |
---|
29 | // Retrieve the main module |
---|
30 | bpl::object import_ = bpl::import("import_"); |
---|
31 | int value = bpl::extract<int>(import_.attr("value")) BOOST_EXTRACT_WORKAROUND; |
---|
32 | std::cout << value << std::endl; |
---|
33 | BOOST_TEST(value == 42); |
---|
34 | } |
---|
35 | |
---|
36 | int main(int argc, char **argv) |
---|
37 | { |
---|
38 | BOOST_TEST(argc == 2); |
---|
39 | |
---|
40 | // Initialize the interpreter |
---|
41 | Py_Initialize(); |
---|
42 | |
---|
43 | if (bpl::handle_exception(boost::bind(import_test, argv))) |
---|
44 | { |
---|
45 | if (PyErr_Occurred()) |
---|
46 | { |
---|
47 | BOOST_ERROR("Python Error detected"); |
---|
48 | PyErr_Print(); |
---|
49 | } |
---|
50 | else |
---|
51 | { |
---|
52 | BOOST_ERROR("A C++ exception was thrown for which " |
---|
53 | "there was no exception handler registered."); |
---|
54 | } |
---|
55 | } |
---|
56 | |
---|
57 | // Boost.Python doesn't support Py_Finalize yet. |
---|
58 | // Py_Finalize(); |
---|
59 | return boost::report_errors(); |
---|
60 | } |
---|
61 | |
---|
62 | // Including this file makes sure |
---|
63 | // that on Windows, any crashes (e.g. null pointer dereferences) invoke |
---|
64 | // the debugger immediately, rather than being translated into structured |
---|
65 | // exceptions that can interfere with debugging. |
---|
66 | #include "module_tail.cpp" |
---|