Ticket #44274: PyMindAgent.cc

File PyMindAgent.cc, 1.8 KB (added by dbl001 (dbl), 10 years ago)
Line 
1
2#include "PyMindAgent.h"
3
4#include <opencog/server/CogServer.h>
5
6#include "opencog/agent_finder_types.h"
7#include "opencog/agent_finder_api.h"
8
9using namespace opencog;
10
11PyMindAgent::PyMindAgent(CogServer& cs,
12                         const std::string& _moduleName,
13                         const std::string& _className) :
14    Agent(cs)
15{
16    PyGILState_STATE gstate;
17    gstate = PyGILState_Ensure(); 
18    import_opencog__agent_finder();
19    moduleName = _moduleName;
20    className = _className;
21    // call out to our helper module written in cython
22    pyagent = instantiate_agent(moduleName, className, this);
23    PyGILState_Release(gstate); 
24    if (pyagent == Py_None)
25        throw RuntimeException(TRACE_INFO, "Error creating Python MindAgent");
26}
27
28const ClassInfo& PyMindAgent::classinfo() const
29{ 
30    static const ClassInfo _ci("opencog::PyMindAgent(" + moduleName+"."+className+")");
31    return _ci;
32}
33
34static bool in_fini = false;
35#if __GNUC__
36static __attribute__ ((destructor (65535))) void pyagent_fini(void)
37{
38    in_fini = true;
39}
40#endif
41
42PyMindAgent::~PyMindAgent()
43{
44    // Do nothing if we are in finalizer ... because at this point,
45    // python is probably already dead, and doing the below will just
46    // segfault.
47    if (in_fini) return;
48
49    // Still fails XXX don't know how to fix this...
50    // Maybe we can ask python if its been finalized?
51    return;
52
53    // decrement python object reference counter
54    PyGILState_STATE gstate = PyGILState_Ensure(); 
55    Py_DECREF(pyagent);
56    PyGILState_Release(gstate); 
57}
58
59void PyMindAgent::run()
60{
61    std::string result = run_agent(pyagent, &_cogserver.getAtomSpace());
62   
63    // run_agent only returns a string if it is propagating an exception
64    if (result.size() > 0) {
65        throw RuntimeException(result.c_str(),
66                               "PyMindAgent triggered runtime exception.");
67    }
68}
69