Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nanobind: use loads and dumps as callable #3043

Merged
merged 10 commits into from
Aug 15, 2024
46 changes: 15 additions & 31 deletions src/nrnpython/nrnpy_p2h.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -635,19 +635,14 @@

// note that *size includes the null terminating character if it exists
static std::vector<char> pickle(PyObject* p) {
PyObject* arg = PyTuple_Pack(1, p);
PyObject* r = nrnpy_pyCallObject(dumps.ptr(), arg);
Py_XDECREF(arg);
nb::list args{};
args.append(nb::borrow(p));
auto r = nb::borrow<nb::bytes>(dumps(*args));
alkino marked this conversation as resolved.
Show resolved Hide resolved
if (!r && PyErr_Occurred()) {
PyErr_Print();
}
assert(r);
assert(PyBytes_Check(r));
std::size_t size = PyBytes_Size(r);
char* buf = PyBytes_AsString(r);
std::vector<char> ret(buf, buf + size);
Py_XDECREF(r);
return ret;
return std::vector<char>(r.c_str(), r.c_str() + r.size());
}

static std::vector<char> po2pickle(Object* ho) {
Expand Down Expand Up @@ -743,43 +738,32 @@
// fname is a pickled callable, narg is the number of args on the
// hoc stack with types double, char*, hoc Vector, and PythonObject
// callable return must be pickleable.
PyObject* args = 0;
PyObject* result = 0;
PyObject* callable;

setpickle();
PyObject* ps = PyBytes_FromStringAndSize(fname.data(), fname.size());
args = PyTuple_Pack(1, ps);
callable = nrnpy_pyCallObject(loads.ptr(), args);
nb::bytes ps(fname.data(), fname.size());
nb::list args{};
args.append(ps);

auto callable = nb::borrow<nb::callable>(loads(*args));
assert(callable);
Py_XDECREF(args);
Py_XDECREF(ps);

args = PyTuple_New(narg);
args.clear();
for (int i = 0; i < narg; ++i) {
PyObject* arg = nrnpy_hoc_pop("call_picklef");
if (PyTuple_SetItem(args, narg - 1 - i, arg)) {
assert(0);
}
// Py_XDECREF(arg);
nb::object arg = nb::steal(nrnpy_hoc_pop("call_picklef"));
args.append(arg);
}
result = nrnpy_pyCallObject(callable, args);
Py_DECREF(callable);
Py_DECREF(args);
nb::object result = callable(*args);
if (!result) {
char* mes = nrnpyerr_str();
if (mes) {
Fprintf(stderr, "%s\n", mes);
std::cerr << mes << std::endl;

Check warning on line 758 in src/nrnpython/nrnpy_p2h.cpp

View check run for this annotation

Codecov / codecov/patch

src/nrnpython/nrnpy_p2h.cpp#L758

Added line #L758 was not covered by tests
free(mes);
hoc_execerror("PyObject method call failed:", NULL);
}
if (PyErr_Occurred()) {
PyErr_Print();
}
}
auto rs = pickle(result);
Py_XDECREF(result);
return rs;
return pickle(result.ptr());
}

#include "nrnmpi.h"
Expand Down
Loading