static char *cpython_import_callback(void *ctx_, const char *base, const char *rel, char **found_here, int *success) { const struct ImportCtx *ctx = ctx_; PyObject *arglist, *result; char *out; arglist = Py_BuildValue("(s, s)", base, rel); result = PyEval_CallObject(ctx->callback, arglist); Py_DECREF(arglist); if (result == NULL) { // Get string from exception char *out = jsonlang_str(ctx->vm, exc_to_str()); *success = 0; PyErr_Clear(); return out; } if (!PyTuple_Check(result)) { out = jsonlang_str(ctx->vm, "import_callback did not return a tuple"); *success = 0; } else if (PyTuple_Size(result) != 2) { out = jsonlang_str(ctx->vm, "import_callback did not return a tuple (size 2)"); *success = 0; } else { PyObject *file_name = PyTuple_GetItem(result, 0); PyObject *file_content = PyTuple_GetItem(result, 1); if (!PyString_Check(file_name) || !PyString_Check(file_content)) { out = jsonlang_str(ctx->vm, "import_callback did not return a pair of strings"); *success = 0; } else { const char *found_here_cstr = PyString_AsString(file_name); const char *content_cstr = PyString_AsString(file_content); *found_here = jsonlang_str(ctx->vm, found_here_cstr); out = jsonlang_str(ctx->vm, content_cstr); *success = 1; } } Py_DECREF(result); return out; }
static int function(double x[], double *f, double g[], void *state) { PyObject *py_list, *arglist, *py_grad, *result = NULL; pytnc_state *py_state = (pytnc_state *)state; py_list = PyDoubleArray_AsList(py_state->n, x); if (py_list == NULL) { PyErr_SetString(PyExc_MemoryError, "tnc: memory allocation failed."); goto failure; } arglist = Py_BuildValue("(N)", py_list); result = PyEval_CallObject(py_state->py_function, arglist); Py_DECREF(arglist); if (result == NULL) goto failure; if (result == Py_None) { Py_DECREF(result); return 1; } if (!PyArg_ParseTuple(result, "dO!", f, &PyList_Type, &py_grad)) { PyErr_SetString(PyExc_ValueError, "tnc: invalid return value from minimized function."); goto failure; } if (PyList_IntoDoubleArray(py_grad, g, py_state->n)) goto failure; Py_DECREF(result); return 0; failure: py_state->failed = 1; Py_XDECREF(result); return 1; }
static OSErr GenericCoercionHandler(const AEDesc *fromDesc, DescType toType, SRefCon refcon, AEDesc *toDesc) { PyObject *handler = (PyObject *)refcon; AEDescObject *fromObject; PyObject *args, *res; PyGILState_STATE state; OSErr err = noErr; state = PyGILState_Ensure(); if ((fromObject = (AEDescObject *)AE_AEDesc_New((AEDesc *)fromDesc)) == NULL) { err = -1; goto cleanup; } if ((args = Py_BuildValue("OO&", fromObject, AE_BuildOSType, &toType)) == NULL) { Py_DECREF(fromObject); err = -1; goto cleanup; } res = PyEval_CallObject(handler, args); fromObject->ob_itself.descriptorType = 'null'; fromObject->ob_itself.dataHandle = NULL; Py_DECREF(args); if (res == NULL) { PySys_WriteStderr("Exception in AE coercion handler function\n"); PyErr_Print(); err = errAECoercionFail; goto cleanup; } if (!AEDesc_Check(res)) { PySys_WriteStderr("AE coercion handler function did not return an AEDesc\n"); Py_DECREF(res); err = errAECoercionFail; goto cleanup; } if (AEDuplicateDesc(&((AEDescObject *)res)->ob_itself, toDesc)) { Py_DECREF(res); err = -1; goto cleanup; } Py_DECREF(res); cleanup: PyGILState_Release(state); return err; }
int PyObject_AsFileDescriptor(PyObject *o) { int fd; PyObject *meth; _Py_IDENTIFIER(fileno); if (PyLong_Check(o)) { fd = _PyLong_AsInt(o); } else if ((meth = _PyObject_GetAttrId(o, &PyId_fileno)) != NULL) { PyObject *fno = PyEval_CallObject(meth, NULL); Py_DECREF(meth); if (fno == NULL) return -1; if (PyLong_Check(fno)) { fd = _PyLong_AsInt(fno); Py_DECREF(fno); } else { PyErr_SetString(PyExc_TypeError, "fileno() returned a non-integer"); Py_DECREF(fno); return -1; } } else { PyErr_SetString(PyExc_TypeError, "argument must be an int, or have a fileno() method."); return -1; } if (fd == -1 && PyErr_Occurred()) return -1; if (fd < 0) { PyErr_Format(PyExc_ValueError, "file descriptor cannot be a negative integer (%i)", fd); return -1; } return fd; }
wxFileOffset OnSysSeek(wxFileOffset off, wxSeekMode mode) { wxPyThreadBlocker blocker; PyObject* arglist = PyTuple_New(2); if (sizeof(wxFileOffset) > sizeof(long)) // wxFileOffset is a 64-bit value... PyTuple_SET_ITEM(arglist, 0, PyLong_FromLongLong(off)); else PyTuple_SET_ITEM(arglist, 0, wxPyInt_FromLong(off)); PyTuple_SET_ITEM(arglist, 1, wxPyInt_FromLong(mode)); PyObject* result = PyEval_CallObject(m_seek, arglist); Py_DECREF(arglist); Py_XDECREF(result); return OnSysTell(); }
/* * Globally defined info callback * * Arguments: ssl - The Connection * where - The part of the SSL code that called us * _ret - The return code of the SSL function that called us * Returns: None */ static void global_info_callback( const SSL * ssl, int where, int _ret ) { ssl_ConnectionObj *conn = (ssl_ConnectionObj *) SSL_get_app_data(ssl); PyObject *argv, *ret; argv = Py_BuildValue("(Oii)", (PyObject *) conn, where, _ret); /* We need to get back our thread state before calling the callback */ ret = PyEval_CallObject(conn->context->info_callback, argv); if ( ret == NULL ) PyErr_Clear(); else Py_DECREF(ret); Py_DECREF(argv); return; }
static xmlSecTransformDataType xmlsec_TransformGetDataTypeMethod(xmlSecTransformPtr transform, xmlSecTransformMode mode, xmlSecTransformCtxPtr transformCtx) { PyObject *args, *result; PyObject *func = NULL; func = xmlHashLookup2(TransformGetDataTypeMethods, transform->id->name, transform->id->href); args = Py_BuildValue((char *) "OiO", wrap_xmlSecTransformPtr(transform), mode, wrap_xmlSecTransformCtxPtr(transformCtx)); Py_INCREF(func); result = PyEval_CallObject(func, args); Py_DECREF(func); Py_DECREF(args); return (PyInt_AsLong(result)); }
void py_empty_cb (struct tgl_state *TLSR, void *cb_extra, int success) { assert (TLSR == TLS); PyObject *callable = cb_extra; PyObject *arglist = NULL; PyObject *result = NULL; if(PyCallable_Check(callable)) { arglist = Py_BuildValue("(O)", success ? Py_True : Py_False); result = PyEval_CallObject(callable, arglist); Py_DECREF(arglist); if(result == NULL) PyErr_Print(); Py_XDECREF(result); } Py_XDECREF(callable); }
int RuleMatch_EndElement(RuleMatchObject *self, PyObject *node, ExpatName *name) { PyObject *handler = self->handlers[Handler_EndElement]; PyObject *args, *result; if (handler != NULL) { /* handler.endElement((namespaceURI, localName), tagName) */ args = Py_BuildValue("O(OO)O", node,name->namespaceURI, name->localName, name->qualifiedName); if (args == NULL) return -1; result = PyEval_CallObject(handler, args); Py_DECREF(args); if (result == NULL) return -1; Py_DECREF(result); } return 0; }
long process_read_step(int slave_id) { PyObject *arg, *mymod, *strfunc; PyObject *pystatus; long step = -1; Py_Initialize(); mymod = PyImport_ImportModule("python_motor"); strfunc = PyObject_GetAttrString(mymod,"read_step"); arg = Py_BuildValue("(i)",slave_id); //printf("before call\n"); pystatus = PyEval_CallObject(strfunc,arg); PyArg_Parse(pystatus,"l",&step); //printf("before finilize\n"); printf("step is %d\n",step); Py_Finalize(); //printf("After finilize\n"); return step; }
static int xmlsec_KeyDataXmlWriteMethod(xmlSecKeyDataId id, xmlSecKeyPtr key, xmlNodePtr node, xmlSecKeyInfoCtxPtr keyInfoCtx) { PyObject *args, *result; PyObject *func = NULL; func = xmlHashLookup(KeyDataXmlWriteMethods, id->name); args = Py_BuildValue((char *) "OOOO", wrap_xmlSecKeyDataId(id), wrap_xmlSecKeyPtr(key), wrap_xmlNodePtr(node), wrap_xmlSecKeyInfoCtxPtr(keyInfoCtx)); Py_INCREF(func); result = PyEval_CallObject(func, args); Py_DECREF(func); Py_DECREF(args); return (PyInt_AsLong(result)); }
static int multi_timer_callback(CURLM *multi, long timeout_ms, void *userp) { CurlMultiObject *self; PyObject *arglist; PyObject *result = NULL; int ret = 0; /* always success */ PYCURL_DECLARE_THREAD_STATE; UNUSED(multi); /* acquire thread */ self = (CurlMultiObject *)userp; if (!PYCURL_ACQUIRE_THREAD_MULTI()) return ret; /* check args */ if (self->t_cb == NULL) goto silent_error; /* run callback */ arglist = Py_BuildValue("(i)", timeout_ms); if (arglist == NULL) goto verbose_error; result = PyEval_CallObject(self->t_cb, arglist); Py_DECREF(arglist); if (result == NULL) goto verbose_error; /* return values from timer callbacks should be ignored */ silent_error: Py_XDECREF(result); PYCURL_RELEASE_THREAD(); return ret; verbose_error: PyErr_Print(); goto silent_error; return 0; }
int process_go_position(int slave_id,float position) { PyObject *arg, *mymod, *strfunc; PyObject *pystatus; int status; Py_Initialize(); mymod = PyImport_ImportModule("python_motor"); strfunc = PyObject_GetAttrString(mymod,"go_position"); arg = Py_BuildValue("(if)",slave_id,position); pystatus = PyEval_CallObject(strfunc,arg); status = PyObject_IsTrue(pystatus); //printf("status is %d\n",status); Py_XDECREF(mymod); Py_XDECREF(strfunc); Py_XDECREF(arg); Py_XDECREF(pystatus); Py_Finalize(); return status; }
/* Dumb greenlet used for controlling the shutdown (originally uWSGI only wait for the hub) */ PyObject *py_uwsgi_gevent_ctrl_gl(PyObject *self, PyObject *args) { for(;;) { PyObject *gevent_sleep_args = PyTuple_New(1); PyTuple_SetItem(gevent_sleep_args, 0, PyInt_FromLong(60)); PyObject *gswitch = PyEval_CallObject(ugevent.greenlet_switch, gevent_sleep_args); // could be NULL on exception if (!gswitch) { // just for being paranid if (PyErr_Occurred()) { PyErr_Clear(); break; } } Py_XDECREF(gswitch); Py_DECREF(gevent_sleep_args); } Py_INCREF(Py_None); return Py_None; }
void * cli_thread(void *params) { PyObject *strret, *strargs; int intret; int fExitOnCtrlC = (int)(size_t)params; dove_status status; PyGILState_STATE gstate; log_debug(PythonLibLogLevel, "Enter"); gstate = PyGILState_Ensure(); do { status = python_lib_embed_initialize_cli(NULL, fExitOnCtrlC); if (status != DOVE_STATUS_OK) { show_print("cli_thread initialize Failure %s", DOVEStatusToString(status)); break; } strargs = Py_BuildValue("()"); if(strargs == NULL) { show_print("cli_thread Py_BuildValue returns NULL"); break; } strret = PyEval_CallObject(Python_Lib_Cli.cli_start, strargs); Py_DECREF(strargs); if (strret == NULL) { show_print("cli_thread PyEval_CallObject returns NULL"); break; } PyArg_Parse(strret, "i", &intret); Py_DECREF(strret); }while(0); PyGILState_Release(gstate); log_debug(PythonLibLogLevel, "Exit"); return ((void *) NULL); }
double _get_match_score(PyObject *py_sequenceA, PyObject *py_sequenceB, PyObject *py_match_fn, int i, int j, char *sequenceA, char *sequenceB, int use_sequence_cstring, double match, double mismatch, int use_match_mismatch_scores) { PyObject *py_A=NULL, *py_B=NULL; PyObject *py_arglist=NULL, *py_result=NULL; double score = 0; if(use_sequence_cstring && use_match_mismatch_scores) { score = (sequenceA[i] == sequenceB[j]) ? match : mismatch; return score; } /* Calculate the match score. */ if(!(py_A = PySequence_GetItem(py_sequenceA, i))) goto _get_match_score_cleanup; if(!(py_B = PySequence_GetItem(py_sequenceB, j))) goto _get_match_score_cleanup; if(!(py_arglist = Py_BuildValue("(OO)", py_A, py_B))) goto _get_match_score_cleanup; if(!(py_result = PyEval_CallObject(py_match_fn, py_arglist))) goto _get_match_score_cleanup; score = PyNumber_AsDouble(py_result); _get_match_score_cleanup: if(py_A) { Py_DECREF(py_A); } if(py_B) { Py_DECREF(py_B); } if(py_arglist) { Py_DECREF(py_arglist); } if(py_result) { Py_DECREF(py_result); } return score; }
/*! * \brief Draw string * * Not optional on the PyDia side. If not implemented a runtime warning * will be generated when called. * * \memberof _DiaPyRenderer */ static void draw_string(DiaRenderer *renderer, const char *text, Point *pos, Alignment alignment, Color *colour) { PyObject *func, *res, *arg, *self = PYDIA_RENDERER (renderer); switch (alignment) { case ALIGN_LEFT: break; case ALIGN_CENTER: break; case ALIGN_RIGHT: break; } func = PyObject_GetAttrString (self, "draw_string"); if (func && PyCallable_Check(func)) { PyObject *opoint = PyDiaPoint_New (pos); PyObject *ocolor = PyDiaColor_New (colour); Py_INCREF(self); Py_INCREF(func); arg = Py_BuildValue ("(sOiO)", text, opoint, alignment, ocolor); if (arg) { res = PyEval_CallObject (func, arg); ON_RES(res, FALSE); } Py_XDECREF (arg); Py_XDECREF (opoint); Py_XDECREF (ocolor); Py_DECREF(func); Py_DECREF(self); } else { /* member not optional */ gchar *msg = g_strdup_printf ("%s.draw_string() implmentation missing.", G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer))); PyErr_Clear(); PyErr_Warn (PyExc_RuntimeWarning, msg); g_free (msg); } }
static pascal OSErr GenericEventHandler(const AppleEvent *request, AppleEvent *reply, refcontype refcon) { PyObject *handler = (PyObject *)refcon; AEDescObject *requestObject, *replyObject; PyObject *args, *res; PyGILState_STATE state; OSErr err = noErr; state = PyGILState_Ensure(); if ((requestObject = (AEDescObject *)AEDesc_New((AppleEvent *)request)) == NULL) { err = -1; goto cleanup; } if ((replyObject = (AEDescObject *)AEDesc_New(reply)) == NULL) { Py_DECREF(requestObject); err = -1; goto cleanup; } if ((args = Py_BuildValue("OO", requestObject, replyObject)) == NULL) { Py_DECREF(requestObject); Py_DECREF(replyObject); err = -1; goto cleanup; } res = PyEval_CallObject(handler, args); requestObject->ob_itself.descriptorType = 'null'; requestObject->ob_itself.dataHandle = NULL; replyObject->ob_itself.descriptorType = 'null'; replyObject->ob_itself.dataHandle = NULL; Py_DECREF(args); if (res == NULL) { PySys_WriteStderr("Exception in AE event handler function\n"); PyErr_Print(); err = -1; goto cleanup; } Py_DECREF(res); cleanup: PyGILState_Release(state); return err; }
static void draw_rounded_rect(DiaRenderer *renderer, Point *ul_corner, Point *lr_corner, Color *fill, Color *stroke, real rounding) { PyObject *func, *res, *arg, *self = PYDIA_RENDERER (renderer); func = PyObject_GetAttrString (self, "draw_rounded_rect"); if (func && PyCallable_Check(func)) { PyObject *orect = PyDiaRectangle_New_FromPoints (ul_corner, lr_corner); PyObject *fill_po, *stroke_po; Py_INCREF(self); Py_INCREF(func); if (fill) fill_po = PyDiaColor_New (fill); else Py_INCREF(Py_None), fill_po = Py_None; if (stroke) stroke_po = PyDiaColor_New (stroke); else Py_INCREF(Py_None), stroke_po = Py_None; arg = Py_BuildValue ("(OOOd)", orect, fill_po, stroke_po, rounding); if (arg) { res = PyEval_CallObject (func, arg); ON_RES(res, FALSE); } Py_XDECREF (arg); Py_XDECREF (fill_po); Py_XDECREF (stroke_po); Py_XDECREF (orect); Py_DECREF(func); Py_DECREF(self); } else { /* member optional */ PyErr_Clear(); /* implementing the same fallback as DiaRenderer would do */ DIA_RENDERER_CLASS (parent_class)->draw_rounded_rect (renderer, ul_corner, lr_corner, fill, stroke, rounding); } }
// Call back into Python, passing a raw nsIInterface object, getting back // the object to actually pass to Python. PyObject * Py_nsISupports::MakeDefaultWrapper(PyObject *pyis, const nsIID &iid) { NS_PRECONDITION(pyis, "NULL pyobject!"); PyObject *obIID = NULL; PyObject *args = NULL; PyObject *mod = NULL; PyObject *ret = NULL; obIID = Py_nsIID::PyObjectFromIID(iid); if (obIID==NULL) goto done; if (g_obFuncMakeInterfaceCount==NULL) { PyObject *mod = PyImport_ImportModule("xpcom.client"); if (mod) g_obFuncMakeInterfaceCount = PyObject_GetAttrString(mod, "MakeInterfaceResult"); Py_XDECREF(mod); } if (g_obFuncMakeInterfaceCount==NULL) goto done; args = Py_BuildValue("OO", pyis, obIID); if (args==NULL) goto done; ret = PyEval_CallObject(g_obFuncMakeInterfaceCount, args); done: if (PyErr_Occurred()) { NS_ABORT_IF_FALSE(ret==NULL, "Have an error, but also a return val!"); PyXPCOM_LogError("Creating an interface object to be used as a result failed\n"); PyErr_Clear(); } Py_XDECREF(mod); Py_XDECREF(args); Py_XDECREF(obIID); if (ret==NULL) // eek - error - return the original with no refcount mod. ret = pyis; else // no error - decref the old object Py_DECREF(pyis); // return our obISupports. If NULL, we are really hosed and nothing we can do. return ret; }
PyObject *uwsgi_python_setup_thread(char *name) { // block signals on this thread sigset_t smask; sigfillset(&smask); #ifndef UWSGI_DEBUG sigdelset(&smask, SIGSEGV); #endif pthread_sigmask(SIG_BLOCK, &smask, NULL); PyThreadState *pts = PyThreadState_New(up.main_thread->interp); pthread_setspecific(up.upt_save_key, (void *) pts); pthread_setspecific(up.upt_gil_key, (void *) pts); UWSGI_GET_GIL; PyObject *threading_module = PyImport_ImportModule("threading"); if (threading_module) { PyObject *threading_module_dict = PyModule_GetDict(threading_module); if (threading_module_dict) { #ifdef PYTHREE PyObject *threading_current = PyDict_GetItemString(threading_module_dict, "current_thread"); #else PyObject *threading_current = PyDict_GetItemString(threading_module_dict, "currentThread"); #endif if (threading_current) { PyObject *current_thread = PyEval_CallObject(threading_current, (PyObject *)NULL); if (!current_thread) { // ignore the error PyErr_Clear(); } else { PyObject_SetAttrString(current_thread, "name", PyString_FromString(name)); Py_INCREF(current_thread); return current_thread; } } } } return NULL; }
static int xmlsec_NodeSetWalkCallback(xmlSecNodeSetPtr nset, xmlNodePtr cur, xmlNodePtr parent, void *data) { PyObject *args, *result; PyObject *func = NULL; func = xmlHashLookup2(NodeSetWalkCallbacks, (const xmlChar *)nset->doc->name, nset->doc->URL); args = Py_BuildValue((char *) "OOOO", wrap_xmlSecNodeSetPtr(nset), wrap_xmlNodePtr(cur), wrap_xmlNodePtr(parent), PyCObject_FromVoidPtr((void *) data, NULL)); /* Protect refcount against reentrant manipulation of callback hash */ Py_INCREF(func); result = PyEval_CallObject(func, args); Py_DECREF(func); Py_DECREF(args); return (PyInt_AsLong(result)); }
int main() { Py_Initialize(); PyRun_SimpleString ("import sys; sys.path.insert(0, '/home/pi/')"); PyObject* pModule = NULL; PyObject* pFunc = NULL; pModule = PyImport_ImportModule("coffeedone"); if(pModule == NULL) { printf("Error importing module."); exit(-1); } pFunc = PyObject_GetAttrString(pModule, "SendEmail"); PyEval_CallObject(pFunc, NULL); Py_Finalize(); return 0; }
/* Receive notification of a processing instruction. */ int RuleMatch_ProcessingInstruction(RuleMatchObject *self, PyObject *node, PyObject *target, PyObject *data) { PyObject *handler = self->handlers[Handler_ProcessingInstruction]; PyObject *args, *result; if (handler != NULL) { /* handler.processingInstruction(node,target,data) */ if ((args = PyTuple_Pack(3, node, target, data)) == NULL) return -1; result = PyEval_CallObject(handler, args); Py_DECREF(args); if (result == NULL) return -1; Py_DECREF(result); } return 0; }
static int xmlsec_TransformNodeWriteMethod(xmlSecTransformPtr transform, xmlNodePtr node, xmlSecTransformCtxPtr transformCtx) { PyObject *args, *result; PyObject *func = NULL; func = xmlHashLookup2(TransformNodeWriteMethods, transform->id->name, transform->id->href); args = Py_BuildValue((char *) "OOO", wrap_xmlSecTransformPtr(transform), wrap_xmlNodePtr(node), wrap_xmlSecTransformCtxPtr(transformCtx)); Py_INCREF(func); result = PyEval_CallObject(func, args); Py_DECREF(func); Py_DECREF(args); return (PyInt_AsLong(result)); }
PyObject * PyObject_CallObject(PyObject *o, PyObject *a) { PyObject *r; PyObject *args = a; if (args == NULL) { args = PyTuple_New(0); if (args == NULL) return NULL; } r = PyEval_CallObject(o, args); if (args != a) { Py_DECREF(args); } return r; }
static void MacOS_HighLevelEventProc(EventRecord *e) { if (MacOS_HighLevelEventHandler != NULL) { PyObject *args = PyMac_BuildEventRecord(e); PyObject *res; if (args == NULL) res = NULL; else { res = PyEval_CallObject(MacOS_HighLevelEventHandler, args); Py_DECREF(args); } if (res == NULL) { fprintf(stderr, "Exception in MacOS_HighLevelEventProc:\n"); PyErr_Print(); } else Py_DECREF(res); } }
PyObject *x_exception_from_event(X11Display_PyObject *display, XErrorEvent *error) { PyObject *args, *exc_class, *exc; char strerror[64]; if (!display || display->x11_error_class == Py_None) { // This shouldn't happen. exc_class = PyExc_SystemError; sprintf(strerror, "Received error code %d for unknown X11 Display", error->error_code); args = Py_BuildValue("(s)", strerror); } else { exc_class = display->x11_error_class; XGetErrorText(display->display, error->error_code, strerror, 63); args = Py_BuildValue("(iiiis)", error->serial, error->error_code, error->request_code, error->minor_code, strerror); } exc = PyEval_CallObject(exc_class, args); Py_DECREF(args); return exc; }
static void xmlsec_PtrDebugXmlDumpItemMethod(xmlSecPtr ptr, FILE *output) { xmlSecPtrListPtr list; PyObject *args, *result; PyObject *func = NULL; list = (xmlSecPtrListPtr) ptr; func = xmlHashLookup(PtrDebugXmlDumpItemMethods, list->id->name); /* FIXME */ args = Py_BuildValue((char *) "OO", wrap_xmlSecPtr(ptr), PyFile_FromFile(output, NULL, NULL, NULL)); /* Protect refcount against reentrant manipulation of callback hash */ Py_INCREF(func); result = PyEval_CallObject(func, args); Py_DECREF(func); Py_DECREF(args); Py_XDECREF(result); }
PyObject *PyCodec_Encode(PyObject *object, const char *encoding, const char *errors) { PyObject *encoder = NULL; PyObject *args = NULL, *result = NULL; PyObject *v; encoder = PyCodec_Encoder(encoding); if (encoder == NULL) goto onError; args = args_tuple(object, errors); if (args == NULL) goto onError; result = PyEval_CallObject(encoder,args); if (result == NULL) goto onError; if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 2) { PyErr_SetString(PyExc_TypeError, "encoder must return a tuple (object,integer)"); goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); /* We don't check or use the second (integer) entry. */ Py_DECREF(args); Py_DECREF(encoder); Py_DECREF(result); return v; onError: Py_XDECREF(result); Py_XDECREF(args); Py_XDECREF(encoder); return NULL; }