comparison oct-py-eval.cc @ 351:040aff46e4db

Refactor calling a Python function into a set of wrapper functions * oct-py-eval.cc, oct-py-eval.h (pytave::py_call_function): New function overloads to call a Python function in various ways. * pycall.cc (Fpycall): Use pytave::py_call_function.
author Mike Miller <mtmiller@octave.org>
date Wed, 17 Aug 2016 14:02:33 -0700
parents 9b862844e6b7
children 4c2b748eaea0
comparison
equal deleted inserted replaced
350:e89a8a37fd8a 351:040aff46e4db
24 # include <config.h> 24 # include <config.h>
25 #endif 25 #endif
26 26
27 #include <string> 27 #include <string>
28 #include <boost/python.hpp> 28 #include <boost/python.hpp>
29 #include <octave/ov.h>
30 #include <octave/ovl.h>
29 31
30 #include "oct-py-eval.h" 32 #include "oct-py-eval.h"
33 #include "oct-py-util.h"
34 #include "octave_to_python.h"
31 35
32 namespace pytave 36 namespace pytave
33 { 37 {
38
39 PyObject *
40 py_call_function (const std::string& func, const octave_value_list& args)
41 {
42 // FIXME: factor out parsing of string into a function reference
43 boost::python::object obj;
44 get_object_from_python (func, obj);
45 return py_call_function (obj.ptr (), args);
46 }
47
48 PyObject *
49 py_call_function (const std::string& func, PyObject *args, PyObject *kwargs)
50 {
51 // FIXME: factor out parsing of string into a function reference
52 boost::python::object obj;
53 get_object_from_python (func, obj);
54 return py_call_function (obj.ptr (), args, kwargs);
55 }
56
57 PyObject *
58 py_call_function (PyObject *callable, const octave_value_list& args)
59 {
60 PyObject *kwargs = 0;
61 PyObject *args_list = PyList_New (0);
62 if (! args_list)
63 octave_throw_bad_alloc ();
64
65 for (int i = 0; i < args.length (); ++i)
66 {
67 boost::python::object arg;
68 pytave::octvalue_to_pyobj (arg, args(i));
69 PyObject *obj = arg.ptr ();
70
71 if (pytave::is_py_kwargs_argument (obj))
72 kwargs = pytave::update_py_dict (kwargs, obj);
73 else
74 {
75 Py_INCREF (obj);
76 PyList_Append (args_list, obj);
77 }
78 }
79
80 PyObject *args_tuple = PyList_AsTuple (args_list);
81 Py_DECREF (args_list);
82
83 PyObject *retval = py_call_function (callable, args_tuple, kwargs);
84 Py_DECREF (args_tuple);
85 Py_XDECREF (kwargs);
86
87 return retval;
88 }
89
90 PyObject *
91 py_call_function (PyObject *callable, PyObject *args, PyObject *kwargs)
92 {
93 PyObject *retval = PyEval_CallObjectWithKeywords (callable, args, kwargs);
94 if (! retval)
95 throw boost::python::error_already_set ();
96
97 return retval;
98 }
34 99
35 PyObject * 100 PyObject *
36 py_run_string_safe (const std::string& expr, int start, PyObject *globals, 101 py_run_string_safe (const std::string& expr, int start, PyObject *globals,
37 PyObject *locals) 102 PyObject *locals)
38 { 103 {