/* Get the variable part of a module's export symbol name. * Returns a bytes instance. For non-ASCII-named modules, the name is * encoded as per PEP 489. * The hook_prefix pointer is set to either ascii_only_prefix or * nonascii_prefix, as appropriate. */ static PyObject * get_encoded_name(PyObject *name, const char **hook_prefix) { PyObject *tmp; PyObject *encoded = NULL; PyObject *modname = NULL; Py_ssize_t name_len, lastdot; _Py_IDENTIFIER(replace); /* Get the short name (substring after last dot) */ name_len = PyUnicode_GetLength(name); lastdot = PyUnicode_FindChar(name, '.', 0, name_len, -1); if (lastdot < -1) { return NULL; } else if (lastdot >= 0) { tmp = PyUnicode_Substring(name, lastdot + 1, name_len); if (tmp == NULL) return NULL; name = tmp; /* "name" now holds a new reference to the substring */ } else { Py_INCREF(name); } /* Encode to ASCII or Punycode, as needed */ encoded = PyUnicode_AsEncodedString(name, "ascii", NULL); if (encoded != NULL) { *hook_prefix = ascii_only_prefix; } else { if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) { PyErr_Clear(); encoded = PyUnicode_AsEncodedString(name, "punycode", NULL); if (encoded == NULL) { goto error; } *hook_prefix = nonascii_prefix; } else { goto error; } } /* Replace '-' by '_' */ modname = _PyObject_CallMethodId(encoded, &PyId_replace, "cc", '-', '_'); if (modname == NULL) goto error; Py_DECREF(name); Py_DECREF(encoded); return modname; error: Py_DECREF(name); Py_XDECREF(encoded); return NULL; }
/** * Check for errors and log a message. */ void PyApi::CheckForPythonErrors() const { const auto ex = PyErr_Occurred(); if (nullptr != ex) { // if this is a normal exist, then we don't need to show an error message. if (!PyErr_ExceptionMatches(PyExc_SystemExit)) { PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); PyErr_Clear(); std::string message = "<b>Error : </b>An error was raised in the PyAPI."; if (type) { const auto temp_bytes = PyUnicode_AsEncodedString(type, "ASCII", "strict"); if (temp_bytes != nullptr) { message += "<br>"; message += PyBytes_AS_STRING(temp_bytes); // Borrowed pointer Py_DECREF(temp_bytes); } } if (value) { const auto temp_bytes = PyUnicode_AsEncodedString(value, "ASCII", "strict"); if (temp_bytes != nullptr) { message += "<br>"; message += PyBytes_AS_STRING(temp_bytes); // Borrowed pointer Py_DECREF(temp_bytes); } } if (traceback) { const auto temp_bytes = PyUnicode_AsEncodedString(traceback, "ASCII", "strict"); if (temp_bytes != nullptr) { message += "<br>"; message += PyBytes_AS_STRING(temp_bytes); // Borrowed pointer Py_DECREF(temp_bytes); } } Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); // give the error message USES_CONVERSION; const wchar_t* msg = T_A2T(message.c_str()); const unsigned int nElapse = 500; const unsigned int nFadeOut = 10; __super::Say(msg, nElapse, nFadeOut); } } // no more errors. PyErr_Clear(); }
void print_dict(PyObject *dict) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(dict, &pos, &key, &value)) { PyObject* k_str_exc_type = PyObject_Repr(key); PyObject* k_pyStr = PyUnicode_AsEncodedString(k_str_exc_type, "utf-8", "Error ~"); printf("key:%s ---> ", (const char *)PyBytes_AS_STRING(k_pyStr)); PyObject* v_str_exc_type = PyObject_Repr(value); PyObject* v_pyStr = PyUnicode_AsEncodedString(v_str_exc_type, "utf-8", "Error ~"); printf("value:%s\n", PyBytes_AsString(v_pyStr)); } }
PyObject * call_func_now(PyObject *s, const void *g, int nargs, const int args[]) { #if PY_MAJOR_VERSION >= 3 PyObject *nres; #endif PyObject *res, *pyargs = PyTuple_New(nargs); int i; for (i = 0; i < nargs; i++) { res = gen_state_slice(g, args[i], args[i+1]); if (!res) { Py_DECREF(pyargs); return NULL; } PyTuple_SET_ITEM(pyargs, i, res); } res = PyObject_CallObject(SYMOBJ(s)->data.func.f, pyargs); Py_DECREF(pyargs); if (!res) return NULL; #if PY_MAJOR_VERSION >= 3 nres = PyUnicode_AsEncodedString(res, "utf-8", "strict"); Py_DECREF(res); if (!nres) return NULL; return nres; #else // return result return res; #endif }
/** * Convert a Python list of unicode strings to a NULL-terminated UTF8-encoded * char * array. The caller must g_free() each string when finished. * * @param py_strlist The list object. * @param outstr ptr to char ** storage to be filled in. * * @return SRD_OK upon success, a (negative) error code otherwise. * The 'outstr' argument points to a g_malloc()ed char** upon success. * * @private */ SRD_PRIV int py_strseq_to_char(const PyObject *py_strseq, char ***outstr) { PyObject *py_str; int list_len, i; char **out, *str; list_len = PySequence_Size((PyObject *)py_strseq); if (!(out = g_try_malloc(sizeof(char *) * (list_len + 1)))) { srd_err("Failed to g_malloc() 'out'."); return SRD_ERR_MALLOC; } for (i = 0; i < list_len; i++) { if (!(py_str = PyUnicode_AsEncodedString( PySequence_GetItem((PyObject *)py_strseq, i), "utf-8", NULL))) return SRD_ERR_PYTHON; if (!(str = PyBytes_AS_STRING(py_str))) return SRD_ERR_PYTHON; out[i] = g_strdup(str); Py_DECREF(py_str); } out[i] = NULL; *outstr = out; return SRD_OK; }
/* Return a copy of argv[0] encoded in the default encoding. * * Return a newly allocated buffer to be released with free(). * * Return NULL in case of error. If the error shouldn't be ignored, also set * a Python exception. */ static char * get_encoded_arg0(wchar_t *argv0) { PyObject *ua = NULL, *ba = NULL; char *rv = NULL; if (!(ua = PyUnicode_FromWideChar(argv0, -1))) { spt_debug("failed to convert argv[0] to unicode"); PyErr_Clear(); goto exit; } if (!(ba = PyUnicode_AsEncodedString( ua, PyUnicode_GetDefaultEncoding(), "strict"))) { spt_debug("failed to encode argv[0]"); PyErr_Clear(); goto exit; } if (!(rv = strdup(PyBytes_AsString(ba)))) { PyErr_NoMemory(); } exit: Py_XDECREF(ua); Py_XDECREF(ba); return rv; }
static void set_features(const char* name, PyObject *PyFeatures) { Py_ssize_t l, i; PyObject *PyStr; if (!PyFeatures) { /* not specified -> enable all */ ncds_features_enableall(name); } else if ((l = PyList_Size(PyFeatures)) == 0) { /* empty list -> disable all */ ncds_features_disableall(name); } else { /* enable specified */ for (i = 0; i < l; i++) { PyObject *PyUni = PyList_GetItem(PyFeatures, i); Py_INCREF(PyUni); if (!PyUnicode_Check(PyUni)) { Py_DECREF(PyUni); continue; } PyStr = PyUnicode_AsEncodedString(PyUni, "UTF-8", NULL); Py_DECREF(PyUni); if (PyStr == NULL) { continue; } ncds_feature_enable(name, PyBytes_AsString(PyStr)); Py_DECREF(PyStr); } } }
//------------------------------------------------------------------------------------- void PythonApp::onExecScriptCommand(Network::Channel* pChannel, KBEngine::MemoryStream& s) { std::string cmd; s.readBlob(cmd); PyObject* pycmd = PyUnicode_DecodeUTF8(cmd.data(), cmd.size(), NULL); if(pycmd == NULL) { SCRIPT_ERROR_CHECK(); return; } DEBUG_MSG(fmt::format("PythonApp::onExecScriptCommand: size({}), command={}.\n", cmd.size(), cmd)); std::string retbuf = ""; PyObject* pycmd1 = PyUnicode_AsEncodedString(pycmd, "utf-8", NULL); script_.run_simpleString(PyBytes_AsString(pycmd1), &retbuf); if(retbuf.size() == 0) { retbuf = "\r\n"; } // 将结果返回给客户端 Network::Bundle* pBundle = Network::Bundle::ObjPool().createObject(); ConsoleInterface::ConsoleExecCommandCBMessageHandler msgHandler; (*pBundle).newMessage(msgHandler); ConsoleInterface::ConsoleExecCommandCBMessageHandlerArgs1::staticAddToBundle((*pBundle), retbuf); pChannel->send(pBundle); Py_DECREF(pycmd); Py_DECREF(pycmd1); }
static PyObject * strcaps_get_file(PyObject *self, PyObject *args) { // (int) fd / (str) path / (file) file PyObject *file; if (!PyArg_ParseTuple(args, "O", &file)) return NULL; cap_t caps; if (PyFile_Check(file)) caps = cap_get_fd(PyObject_AsFileDescriptor(file)); else if (PyInt_Check(file)) caps = cap_get_fd(PyInt_AsLong(file)); else if (PyString_Check(file)) caps = cap_get_file(PyString_AsString(file)); else if (PyUnicode_Check(file)) { PyObject *file_dec = PyUnicode_AsEncodedString( file, Py_FileSystemDefaultEncoding, "strict" ); if (file_dec == NULL) return NULL; caps = cap_get_file(PyString_AsString(file_dec)); Py_DECREF(file_dec); } else { PyErr_SetString( PyExc_TypeError, "Expecting file object, descriptor int or path string" ); return NULL; } size_t strcaps_len; char *strcaps; if (caps == NULL) { if (errno == ENODATA) { strcaps = "\0"; strcaps_len = 0; } else { PyErr_SetFromErrno(PyExc_OSError); return NULL; } } else strcaps = cap_to_text(caps, &strcaps_len); cap_free(caps); return Py_BuildValue("s#", strcaps, strcaps_len); }; // (str) caps
static PyObject * z_set(void *ptr, PyObject *value, Py_ssize_t size) { if (value == Py_None) { *(char **)ptr = NULL; Py_INCREF(value); return value; } if (PyString_Check(value)) { *(char **)ptr = PyString_AS_STRING(value); Py_INCREF(value); return value; } else if (PyUnicode_Check(value)) { PyObject *str = PyUnicode_AsEncodedString(value, _ctypes_conversion_encoding, _ctypes_conversion_errors); if (str == NULL) return NULL; *(char **)ptr = PyString_AS_STRING(str); return str; } else if (PyInt_Check(value) || PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG *(char **)ptr = (char *)PyInt_AsUnsignedLongLongMask(value); #else *(char **)ptr = (char *)PyInt_AsUnsignedLongMask(value); #endif _RET(value); } PyErr_Format(PyExc_TypeError, "string or integer address expected instead of %s instance", value->ob_type->tp_name); return NULL; }
//------------------------------------------------------------------------------------- void TelnetHandler::processPythonCommand(std::string command) { if(pTelnetServer_->pScript() == NULL || command.size() == 0) return; command += "\n"; PyObject* pycmd = PyUnicode_DecodeUTF8(command.data(), command.size(), NULL); if(pycmd == NULL) { SCRIPT_ERROR_CHECK(); return; } DEBUG_MSG(boost::format("TelnetHandler::processPythonCommand: size(%1%), command=%2%.\n") % command.size() % command); std::string retbuf = ""; PyObject* pycmd1 = PyUnicode_AsEncodedString(pycmd, "utf-8", NULL); pTelnetServer_->pScript()->run_simpleString(PyBytes_AsString(pycmd1), &retbuf); if(retbuf.size() > 0) { // 将结果返回给客户端 Mercury::Bundle bundle; bundle << retbuf; bundle.send(*pEndPoint_); sendEnter(); } Py_DECREF(pycmd); Py_DECREF(pycmd1); }
//----------------------------------------------------------------------------- // cxBuffer_FromObject() // Populate the string buffer from a unicode object. //----------------------------------------------------------------------------- static int cxBuffer_FromObject( udt_Buffer *buf, // buffer to fill PyObject *obj, // object (string or Unicode object) const char *encoding) // encoding to use, if applicable { if (!obj) return cxBuffer_Init(buf); if (encoding && PyUnicode_Check(obj)) { buf->obj = PyUnicode_AsEncodedString(obj, encoding, NULL); if (!buf->obj) return -1; buf->ptr = PyBytes_AS_STRING(buf->obj); buf->size = PyBytes_GET_SIZE(buf->obj); buf->numCharacters = PyUnicode_GET_SIZE(obj); } else if (PyBytes_Check(obj)) { Py_INCREF(obj); buf->obj = obj; buf->ptr = PyBytes_AS_STRING(buf->obj); buf->size = buf->numCharacters = PyBytes_GET_SIZE(buf->obj); #if PY_MAJOR_VERSION < 3 } else if (PyBuffer_Check(obj)) { if (PyObject_AsReadBuffer(obj, &buf->ptr, &buf->size) < 0) return -1; Py_INCREF(obj); buf->obj = obj; buf->numCharacters = buf->size; #endif } else { PyErr_SetString(PyExc_TypeError, CXORA_TYPE_ERROR); return -1; } return 0; }
static PyObject * strcaps_set_file(PyObject *self, PyObject *args) { // (str) caps, (int) fd / (str) path / (file) file char *strcaps; PyObject *file; if (!PyArg_ParseTuple(args, "etO", Py_FileSystemDefaultEncoding, &strcaps, &file)) return NULL; cap_t caps; if ((caps = cap_from_text(strcaps)) == NULL) { PyErr_SetString(PyExc_ValueError, "Invalid capability specification"); PyMem_Free(strcaps); return NULL; } PyMem_Free(strcaps); int err; if (PyFile_Check(file)) err = cap_set_fd(PyObject_AsFileDescriptor(file), caps); else if (PyInt_Check(file)) err = cap_set_fd(PyInt_AsLong(file), caps); else if (PyString_Check(file)) err = cap_set_file(PyString_AsString(file), caps); else if (PyUnicode_Check(file)) { PyObject *file_dec = PyUnicode_AsEncodedString( file, Py_FileSystemDefaultEncoding, "strict" ); if (file_dec == NULL) return NULL; err = cap_set_file(PyString_AsString(file_dec), caps); Py_DECREF(file_dec); } else { PyErr_SetString( PyExc_TypeError, "Expecting file object, descriptor int or path string" ); cap_free(caps); return NULL; } cap_free(caps); if (err) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } Py_RETURN_NONE; };
char * PySpotify_GetConfigString(PyObject *client, const char *attr) { PyObject *py_value, *py_uvalue; char *value; py_value = PyObject_GetAttrString(client, attr); if (!py_value) { PyErr_Format(SpotifyError, "%s not set", attr); return NULL; } if (PyUnicode_Check(py_value)) { py_uvalue = py_value; py_value = PyUnicode_AsEncodedString(py_uvalue, ENCODING, "replace"); Py_DECREF(py_uvalue); } else if (!PyBytes_Check(py_value)) { PyErr_Format(SpotifyError, "configuration value '%s' must be a string/unicode object", attr); return NULL; } value = PyMem_Malloc(strlen(PyBytes_AS_STRING(py_value)) + 1); strcpy(value, PyBytes_AS_STRING(py_value)); Py_DECREF(py_value); return value; }
/* Caller is responsible for free-ing memory with PyMem_Free */ static bool encoded_string_converter(PyObject *o, void *address) { char **target = (char **)address; char *buffer; Py_ssize_t length; if (o == NULL || o == Py_None) { return 1; } if (PyUnicode_Check(o)) o = PyUnicode_AsEncodedString(o, ENCODING, "strict"); else Py_INCREF(o); if (PyString_AsStringAndSize(o, &buffer, &length) == -1) { Py_DECREF(o); return 0; } *target = PyMem_Malloc(length + 1); if (target == NULL) { PyErr_NoMemory(); Py_DECREF(o); return 0; } strcpy(*target, buffer); Py_DECREF(o); return 1; }
void EntityApp<E>::onExecScriptCommand(Mercury::Channel* pChannel, KBEngine::MemoryStream& s) { std::string cmd; s.readBlob(cmd); PyObject* pycmd = PyUnicode_DecodeUTF8(cmd.data(), cmd.size(), NULL); if(pycmd == NULL) { SCRIPT_ERROR_CHECK(); return; } DEBUG_MSG(boost::format("EntityApp::onExecScriptCommand: size(%1%), command=%2%.\n") % cmd.size() % cmd); std::string retbuf = ""; PyObject* pycmd1 = PyUnicode_AsEncodedString(pycmd, "utf-8", NULL); if(script_.run_simpleString(PyBytes_AsString(pycmd1), &retbuf) == 0) { // 将结果返回给客户端 Mercury::Bundle bundle; ConsoleInterface::ConsoleExecCommandCBMessageHandler msgHandler; bundle.newMessage(msgHandler); ConsoleInterface::ConsoleExecCommandCBMessageHandlerArgs1::staticAddToBundle(bundle, retbuf); bundle.send(this->getNetworkInterface(), pChannel); } Py_DECREF(pycmd); Py_DECREF(pycmd1); }
PyObject* __call__(PyObject* self_, PyObject* args, PyObject**) { PyObject* status_ = nullptr; PyObject* headers = nullptr; if (!PyArg_ParseTuple(args, "OO", &status_, &headers)) { return nullptr; } // - Extract out the status lines auto self = (WsgiStartResponseObject*)self_; std::string status( PyBytes_AS_STRING(PyUnicode_AsEncodedString(status_, "utf-8", "Error"))); size_t code; std::string message; std::tie(code, message) = ParseMessageLine(status); // - Extract out the headers assert(PyList_CheckExact(headers)); fcgi::HttpHeader header(code, message); for (Py_ssize_t i = 0; i < PyList_Size(headers); ++i) { PyObject* pair = PyList_GET_ITEM(headers, i); assert(PyTuple_CheckExact(pair)); PyObject* nameObj = PyTuple_GET_ITEM(pair, 0); PyObject* valueObj = PyTuple_GET_ITEM(pair, 1); std::string name( PyBytes_AS_STRING(PyUnicode_AsEncodedString(nameObj, "utf-8", "Error"))); std::string value( PyBytes_AS_STRING(PyUnicode_AsEncodedString(valueObj, "utf-8", "Error"))); Py_DECREF(pair); header.Add(name, value); } // - Send header response assert(nullptr != self); assert(nullptr != self->res); self->res->SetResponse(header); Py_RETURN_NONE; }
static int tok_stdin_decode(struct tok_state *tok, char **inp) { PyObject *enc, *sysstdin, *decoded, *utf8; const char *encoding; char *converted; if (PySys_GetFile((char *)"stdin", NULL) != stdin) return 0; sysstdin = PySys_GetObject("stdin"); if (sysstdin == NULL || !PyFile_Check(sysstdin)) return 0; enc = ((PyFileObject *)sysstdin)->f_encoding; if (enc == NULL || !PyString_Check(enc)) return 0; Py_INCREF(enc); encoding = PyString_AsString(enc); decoded = PyUnicode_Decode(*inp, strlen(*inp), 0, encoding, NULL); if (decoded == NULL) goto error_clear; utf8 = PyUnicode_AsEncodedString(decoded, "utf-8", NULL); Py_DECREF(decoded); if (utf8 == NULL) goto error_clear; assert(PyString_Check(utf8)); converted = new_string(PyString_AS_STRING(utf8), PyString_GET_SIZE(utf8)); Py_DECREF(utf8); if (converted == NULL) goto error_nomem; PyMem_FREE(*inp); *inp = converted; if (tok->encoding != NULL) PyMem_FREE(tok->encoding); tok->encoding = new_string(encoding, strlen(encoding)); if (tok->encoding == NULL) goto error_nomem; Py_DECREF(enc); return 0; error_nomem: Py_DECREF(enc); tok->done = E_NOMEM; return -1; error_clear: /* Fallback to iso-8859-1: for backward compatibility */ Py_DECREF(enc); PyErr_Clear(); return 0; }
int PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value) { PyTypeObject *tp = v->ob_type; int err; if (!PyString_Check(name)){ #ifdef Py_USING_UNICODE /* The Unicode to string conversion is done here because the existing tp_setattro slots expect a string object as name and we wouldn't want to break those. */ if (PyUnicode_Check(name)) { name = PyUnicode_AsEncodedString(name, NULL, NULL); if (name == NULL) return -1; } else #endif { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return -1; } } else Py_INCREF(name); PyString_InternInPlace(&name); if (tp->tp_setattro != NULL) { err = (*tp->tp_setattro)(v, name, value); Py_DECREF(name); return err; } if (tp->tp_setattr != NULL) { err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value); Py_DECREF(name); return err; } Py_DECREF(name); if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) PyErr_Format(PyExc_TypeError, "'%.100s' object has no attributes " "(%s .%.100s)", tp->tp_name, value==NULL ? "del" : "assign to", PyString_AS_STRING(name)); else PyErr_Format(PyExc_TypeError, "'%.100s' object has only read-only attributes " "(%s .%.100s)", tp->tp_name, value==NULL ? "del" : "assign to", PyString_AS_STRING(name)); return -1; }
static int wrap_setattro(PyObject *self, PyObject *name, PyObject *value) { PyObject *wrapped; PyObject *descriptor; const char *name_as_string; int res = -1; #if PY_MAJOR_VERSION < 3 && defined(Py_USING_UNICODE) /* The Unicode to string conversion is done here because the existing tp_setattro slots expect a string object as name (except under Python 3) and we wouldn't want to break those. */ if (PyUnicode_Check(name)) { name = PyUnicode_AsEncodedString(name, NULL, NULL); if (name == NULL) return -1; } else #endif if (!IS_STRING(name)){ PyErr_SetString(PyExc_TypeError, "attribute name must be string"); return -1; } else Py_INCREF(name); descriptor = WrapperType_Lookup(self->ob_type, name); if (descriptor != NULL #if PY_MAJOR_VERSION < 3 // This is always true in Python 3 (I think) && PyType_HasFeature(descriptor->ob_type, Py_TPFLAGS_HAVE_CLASS) #endif && descriptor->ob_type->tp_descr_set != NULL) { res = descriptor->ob_type->tp_descr_set(descriptor, self, value); goto finally; } name_as_string = MAKE_STRING(name); wrapped = Proxy_GET_OBJECT(self); if (wrapped == NULL) { PyErr_Format(PyExc_RuntimeError, "object is NULL; requested to set attribute '%s'", name_as_string); goto finally; } res = PyObject_SetAttr(wrapped, name, value); finally: Py_DECREF(name); return res; }
static PyObject *setCapabilities(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *PyCpblts; Py_ssize_t l, i; int ret; char *item; static char *kwlist[] = {"list", NULL}; PyObject *PyStr; if (! PyArg_ParseTupleAndKeywords(args, keywds, "O!", kwlist, &PyList_Type, &PyCpblts)) { return (NULL); } if ((l = PyList_Size(PyCpblts)) < 1) { PyErr_SetString(PyExc_ValueError, "The capabilities list must not be empty."); return (NULL); } nc_cpblts_free(global_cpblts); global_cpblts = nc_cpblts_new(NULL); for (i = 0; i < l; i++) { PyObject *PyUni = PyList_GetItem(PyCpblts, i); Py_INCREF(PyUni); if (!PyUnicode_Check(PyUni)) { PyErr_SetString(PyExc_TypeError, "Capabilities list must contain strings."); nc_cpblts_free(global_cpblts); global_cpblts = NULL; Py_DECREF(PyUni); return (NULL); } PyStr = PyUnicode_AsEncodedString(PyUni, "UTF-8", NULL); Py_DECREF(PyUni); if (PyStr == NULL) { nc_cpblts_free(global_cpblts); global_cpblts = NULL; return (NULL); } item = PyBytes_AsString(PyStr); if (item == NULL) { nc_cpblts_free(global_cpblts); global_cpblts = NULL; Py_DECREF(PyStr); return (NULL); } ret = nc_cpblts_add(global_cpblts, item); Py_DECREF(PyStr); if (ret != EXIT_SUCCESS) { nc_cpblts_free(global_cpblts); global_cpblts = NULL; return (NULL); } } Py_RETURN_NONE; }
char * PyString_AsString(PyObject *unicode) { char *rv; PyObject *o = PyUnicode_AsEncodedString(unicode, GetDatabaseEncodingName(), NULL); errorCheck(); rv = pstrdup(PyBytes_AsString(o)); Py_XDECREF(o); return rv; }
/* Returns a PyObject with the contents of the given unicode string object converted to a named charset. If an error occurs during the conversion, NULL will be returned and a python exception will be set. */ static PyObject * unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset) { PyObject *string; /* Translate string to named charset. */ string = PyUnicode_AsEncodedString (unicode_str, charset, NULL); if (string == NULL) return NULL; return string; }
PyObject * microprotocol_getquoted(PyObject *obj, connectionObject *conn) { PyObject *res = NULL; PyObject *prepare = NULL; PyObject *adapted; if (!(adapted = microprotocols_adapt(obj, (PyObject*)&isqlquoteType, NULL))) { goto exit; } Dprintf("microprotocol_getquoted: adapted to %s", Py_TYPE(adapted)->tp_name); /* if requested prepare the object passing it the connection */ if (conn) { if ((prepare = PyObject_GetAttrString(adapted, "prepare"))) { res = PyObject_CallFunctionObjArgs( prepare, (PyObject *)conn, NULL); if (res) { Py_DECREF(res); res = NULL; } else { goto exit; } } else { /* adapted.prepare not found */ PyErr_Clear(); } } /* call the getquoted method on adapted (that should exist because we adapted to the right protocol) */ res = PyObject_CallMethod(adapted, "getquoted", NULL); /* Convert to bytes. */ if (res && PyUnicode_CheckExact(res)) { PyObject *b; const char *codec; codec = (conn && conn->codec) ? conn->codec : "utf8"; b = PyUnicode_AsEncodedString(res, codec, NULL); Py_DECREF(res); res = b; } exit: Py_XDECREF(adapted); Py_XDECREF(prepare); /* we return res with one extra reference, the caller shall free it */ return res; }
void PyCall(char* pyName, char* pyFunc, char* result, int varCount, ...) { PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pValue; char * tempResult = 0; pName = PyUnicode_FromString(pyName); pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, pyFunc); va_list varList; va_start(varList, varCount); if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(varCount); for (int i = 0; i < varCount; i++) { pValue = PyUnicode_FromString(va_arg(varList, char*)); PyTuple_SetItem(pArgs, i, pValue); } va_end(varList); pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { Py_DECREF(pValue); } if (PyUnicode_Check(pValue)) { PyObject * tempObj = PyUnicode_AsEncodedString(pValue, "ASCII", "strict"); if (tempObj != NULL) { tempResult = PyBytes_AsString(tempObj); strcpy(result, tempResult); Py_DECREF(tempObj); } } }
static PyObject * dec_utf8(const char *enc, const char *text, size_t len) { PyObject *ret = NULL; PyObject *unicode_text = PyUnicode_DecodeUTF8(text, len, 0, "replace"); if (unicode_text) { ret = PyUnicode_AsEncodedString(unicode_text, enc, "replace"); Py_DECREF(unicode_text); } if (!ret) { PyErr_Clear(); } return ret; }
static int wrap_setattro(PyObject *self, PyObject *name, PyObject *value) { PyObject *wrapped; PyObject *descriptor; int res = -1; #ifdef Py_USING_UNICODE /* The Unicode to string conversion is done here because the existing tp_setattro slots expect a string object as name and we wouldn't want to break those. */ if (PyUnicode_Check(name)) { name = PyUnicode_AsEncodedString(name, NULL, NULL); if (name == NULL) return -1; } else #endif if (!PyString_Check(name)){ PyErr_SetString(PyExc_TypeError, "attribute name must be string"); return -1; } else Py_INCREF(name); descriptor = WrapperType_Lookup(self->ob_type, name); if (descriptor != NULL) { if (PyType_HasFeature(descriptor->ob_type, Py_TPFLAGS_HAVE_CLASS) && descriptor->ob_type->tp_descr_set != NULL) { res = descriptor->ob_type->tp_descr_set(descriptor, self, value); } else { PyErr_Format(PyExc_TypeError, "Tried to set attribute '%s' on wrapper, but it is not" " a data descriptor", PyString_AS_STRING(name)); } goto finally; } wrapped = Proxy_GET_OBJECT(self); if (wrapped == NULL) { PyErr_Format(PyExc_RuntimeError, "object is NULL; requested to set attribute '%s'", PyString_AS_STRING(name)); goto finally; } res = PyObject_SetAttr(wrapped, name, value); finally: Py_DECREF(name); return res; }
static PyObject *journal_sendv(PyObject *self, PyObject *args) { struct iovec *iov = NULL; int argc; int i, r; PyObject *ret = NULL; PyObject **encoded; /* Allocate an array for the argument strings */ argc = PyTuple_Size(args); encoded = alloca0(argc * sizeof(PyObject*)); /* Allocate sufficient iovector space for the arguments. */ iov = alloca(argc * sizeof(struct iovec)); /* Iterate through the Python arguments and fill the iovector. */ for (i = 0; i < argc; ++i) { PyObject *item = PyTuple_GetItem(args, i); char *stritem; Py_ssize_t length; if (PyUnicode_Check(item)) { encoded[i] = PyUnicode_AsEncodedString(item, "utf-8", "strict"); if (encoded[i] == NULL) goto out; item = encoded[i]; } if (PyBytes_AsStringAndSize(item, &stritem, &length)) goto out; iov[i].iov_base = stritem; iov[i].iov_len = length; } /* Send the iovector to the journal. */ r = sd_journal_sendv(iov, argc); if (r < 0) { errno = -r; PyErr_SetFromErrno(PyExc_IOError); goto out; } /* End with success. */ Py_INCREF(Py_None); ret = Py_None; out: for (i = 0; i < argc; ++i) Py_XDECREF(encoded[i]); return ret; }
/* Consume a "file-like" object and write bytes to stdout */ static PyObject *py_consume_file(PyObject *self, PyObject *args) { PyObject *obj; PyObject *read_meth; PyObject *result = NULL; PyObject *read_args; if (!PyArg_ParseTuple(args,"O", &obj)) { return NULL; } /* Get the read method of the passed object */ if ((read_meth = PyObject_GetAttrString(obj, "read")) == NULL) { return NULL; } /* Build the argument list to read() */ read_args = Py_BuildValue("(i)", CHUNK_SIZE); while (1) { PyObject *data; PyObject *enc_data; char *buf; Py_ssize_t len; /* Call read() */ if ((data = PyObject_Call(read_meth, read_args, NULL)) == NULL) { goto final; } /* Check for EOF */ if (PySequence_Length(data) == 0) { Py_DECREF(data); break; } /* Encode Unicode as Bytes for C */ if ((enc_data = PyUnicode_AsEncodedString(data, "utf-8", "strict")) == NULL) { Py_DECREF(data); goto final; } /* Extract underlying buffer data */ PyBytes_AsStringAndSize(enc_data, &buf, &len); /* Write to stdout (replace with something more useful) */ write(1, buf, len); /* Cleanup */ Py_DECREF(enc_data); Py_DECREF(data); }
/* Pobieranie obiektu podobnego do pliku i wyświetlanie bajtów w strumieniu stdout */ static PyObject *py_consume_file(PyObject *self, PyObject *args) { PyObject *obj; PyObject *read_meth; PyObject *result = NULL; PyObject *read_args; if (!PyArg_ParseTuple(args,"O", &obj)) { return NULL; } /* Pobieranie metody read przekazanego obiektu */ if ((read_meth = PyObject_GetAttrString(obj, "read")) == NULL) { return NULL; } /* Tworzenie listy argumentów dla metody read() */ read_args = Py_BuildValue("(i)", CHUNK_SIZE); while (1) { PyObject *data; PyObject *enc_data; char *buf; Py_ssize_t len; /* Wywołanie metody read() */ if ((data = PyObject_Call(read_meth, read_args, NULL)) == NULL) { goto final; } /* Wykrywanie końca pliku */ if (PySequence_Length(data) == 0) { Py_DECREF(data); break; } /* Kodowanie znaków Unicode jako bajtów na potrzeby kodu w języku C */ if ((enc_data = PyUnicode_AsEncodedString(data, "utf-8", "strict")) == NULL) { Py_DECREF(data); goto final; } /* Pobieranie danych z bufora */ PyBytes_AsStringAndSize(enc_data, &buf, &len); /* Wyświetlanie w strumieniu stdout (do zastąpienia bardziej użytecznym kodem) */ write(1, buf, len); /* Operacje porządkujące */ Py_DECREF(enc_data); Py_DECREF(data); }