Skip to content

Instantly share code, notes, and snippets.

@JacquesLucke
Created October 11, 2018 09:00
Show Gist options
  • Save JacquesLucke/9935a5daec53deffb7a21c3821e1383f to your computer and use it in GitHub Desktop.
Save JacquesLucke/9935a5daec53deffb7a21c3821e1383f to your computer and use it in GitHub Desktop.
static PyObject *get_external_function(const char *module_name, const char *function_name)
{
PyObject *module = PyImport_ImportModule(module_name);
PyObject *globals = PyModule_GetDict(module);
PyObject *function = PyDict_GetItemString(globals, function_name);
Py_DecRef(module);
return function;
}
static PyObject *call_external_method(
const char *module_name,
const char *function_name,
PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *function = get_external_function(module_name, function_name);
int args_length = PyTuple_Size(args);
PyObject *new_args = PyTuple_New(1 + args_length);
Py_IncRef(self);
PyTuple_SET_ITEM(new_args, 0, self);
for (int i = 0; i < args_length; i++) {
PyObject *value = PyTuple_GetItem(args, i);
Py_IncRef(value);
PyTuple_SET_ITEM(new_args, i + 1, value);
}
PyObject *ret = PyEval_CallObjectWithKeywords(function, new_args, kwds);
Py_DecRef(new_args);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment