Skip to content

Commit e613f8d

Browse files
committed
trying to get a c++ object to be used as a python object...
1 parent 264027f commit e613f8d

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

eval-set-object/CMakeLists.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
cmake_minimum_required(VERSION 3.4)
2+
project(scripting)
3+
4+
set(PYBIND11_PYTHON_VERSION 3.4)
5+
6+
FIND_PACKAGE(pybind11 CONFIG)
7+
8+
ADD_EXECUTABLE(scripting src/main.cpp)
9+
TARGET_LINK_LIBRARIES(scripting ${PYTHON_LIBRARIES})
10+
TARGET_LINK_LIBRARIES(scripting pybind11::embed)

eval-set-object/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# A python script running a PyQt5 input dialog and setting a c++ variable with the value
2+
3+
~~~.sh
4+
$ mkdir build
5+
$ cmake -Dpybind11_DIR=/home/ale/bin/pybind11/share/cmake/pybind11 ..
6+
$ make
7+
$ ./scripting
8+
~~~

eval-set-object/src/main.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#include <iostream>
2+
#include <pybind11/pybind11.h>
3+
#include <pybind11/embed.h>
4+
5+
namespace py = pybind11;
6+
7+
// for the _a string litteral
8+
// http://pybind11.readthedocs.io/en/stable/basics.html#keyword-arguments
9+
using namespace pybind11::literals;
10+
11+
struct Foo { int bar = 1; };
12+
13+
14+
PYBIND11_EMBEDDED_MODULE(foo_module, m) {
15+
py::class_<Foo>(m, "Foo").def_readwrite("bar", &Foo::bar);
16+
}
17+
18+
int main()
19+
{
20+
py::scoped_interpreter guard{}; // start the interpreter and keep it alive
21+
22+
Foo foo1, foo2;
23+
24+
auto module = py::module::import("foo_module");
25+
26+
auto locals = py::dict("foo_copy"_a=foo1, "foo_ref"_a=&foo2, **module.attr("__dict__")); // note the &
27+
py::exec(R"(
28+
print(foo_copy.bar);
29+
foo_copy.bar = 5;
30+
print(foo_copy.bar);
31+
foo_ref.bar = 5;
32+
)", py::globals(), locals);
33+
34+
assert(foo1.bar == 1);
35+
assert(foo2.bar == 5);
36+
37+
}

0 commit comments

Comments
 (0)