Add copy constructor and assignment operator to PyAction

This commit is contained in:
Joakim Hove
2020-03-24 08:07:21 +01:00
parent a0ebb2091f
commit 9ce64d5aae
2 changed files with 17 additions and 11 deletions

View File

@@ -41,6 +41,9 @@ public:
PyAction() = default;
PyAction(const std::string& name, RunCount run_count, const std::string& code);
PyAction(const PyAction& other);
PyAction operator=(const PyAction& other);
~PyAction();
static PyAction serializeObject();
@@ -49,7 +52,6 @@ public:
bool operator==(const PyAction& other) const;
PyAction::RunCount run_count() const;
bool active() const;
~PyAction();
/*
Storage is a void pointer to a Python dictionary: py::dict. It is represented

View File

@@ -22,10 +22,6 @@
#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
namespace py = pybind11;
#else
namespace py {
using dict = int;
}
#endif
@@ -76,10 +72,20 @@ std::string PyAction::load(const std::string& input_path, const std::string& fna
PyAction::PyAction(const std::string& name, RunCount run_count, const std::string& code) :
m_name(name),
m_run_count(run_count),
input_code(code),
m_storage( new py::dict() )
input_code(code)
{
#ifdef EMBEDDED_PYTHON
this->m_storage = new py::dict();
#endif
}
PyAction::PyAction(const PyAction& other) :
PyAction(other.name(), other.run_count(), other.code())
{}
PyAction PyAction::operator=(const PyAction& other) {
return PyAction(other);
}
const std::string& PyAction::code() const {
return this->input_code;
@@ -100,19 +106,17 @@ bool PyAction::active() const {
/*
The python variables are reference counted and when the Python dictionary
stored in this->m_storage is destroyed the Python runtime system is involved.
This will fail hard id the Python runtime system has not been initialized. If
This will fail hard if the Python runtime system has not been initialized. If
the python runtime has not been initialized the Python dictionary object will
leak - the leakage is quite harmless, using the PyAction object without a
Python runtime system does not make any sense after all.
*/
PyAction::~PyAction() {
auto dict = static_cast<py::dict *>(this->m_storage);
#ifdef EMBEDDED_PYTHON
auto dict = static_cast<py::dict *>(this->m_storage);
if (Py_IsInitialized())
delete dict;
#else
delete dict;
#endif
}