当前位置: 首页>>代码示例>>C++>>正文


C++ PyUnicode_AsEncodedString函数代码示例

本文整理汇总了C++中PyUnicode_AsEncodedString函数的典型用法代码示例。如果您正苦于以下问题:C++ PyUnicode_AsEncodedString函数的具体用法?C++ PyUnicode_AsEncodedString怎么用?C++ PyUnicode_AsEncodedString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了PyUnicode_AsEncodedString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: get_encoded_name

/* 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;
}
开发者ID:3lnc,项目名称:cpython,代码行数:59,代码来源:importdl.c

示例2: PyErr_Occurred

/**
 * 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();
}
开发者ID:FFMG,项目名称:myoddweb.piger,代码行数:56,代码来源:pyapi.cpp

示例3: print_dict

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));
	}
}
开发者ID:studiot-jp,项目名称:packet_generator,代码行数:14,代码来源:gettcp.c

示例4: call_func_now

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
}
开发者ID:blackberry,项目名称:ALF,代码行数:32,代码来源:symbol.c

示例5: py_strseq_to_char

/**
 * 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;
}
开发者ID:plaes,项目名称:libsigrokdecode,代码行数:37,代码来源:util.c

示例6: get_encoded_arg0

/* 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;
}
开发者ID:RealImpactAnalytics,项目名称:py-setproctitle,代码行数:36,代码来源:spt_setup.c

示例7: set_features

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);
		}
	}
}
开发者ID:ADTRAN,项目名称:libnetconf,代码行数:30,代码来源:netconf.c

示例8: PyUnicode_DecodeUTF8

//-------------------------------------------------------------------------------------
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);
}
开发者ID:nichunen,项目名称:kbengine,代码行数:35,代码来源:python_app.cpp

示例9: strcaps_get_file

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
开发者ID:mk-fg,项目名称:fgc,代码行数:27,代码来源:strcaps.c

示例10: z_set

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;
}
开发者ID:nanwu,项目名称:pyston,代码行数:33,代码来源:cfield.c

示例11: PyUnicode_DecodeUTF8

//-------------------------------------------------------------------------------------
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);
}
开发者ID:MapleEve,项目名称:kbengine,代码行数:34,代码来源:telnet_handler.cpp

示例12: cxBuffer_FromObject

//-----------------------------------------------------------------------------
// 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;
}
开发者ID:15580056814,项目名称:hue,代码行数:37,代码来源:Buffer.c

示例13: strcaps_set_file

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; };
开发者ID:mk-fg,项目名称:fgc,代码行数:31,代码来源:strcaps.c

示例14: PySpotify_GetConfigString

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;
}
开发者ID:JoeConyers,项目名称:SpotifyRemote,代码行数:27,代码来源:session.c

示例15: encoded_string_converter

/* 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;
}
开发者ID:ZenithDK,项目名称:pyspotify,代码行数:32,代码来源:session.c


注:本文中的PyUnicode_AsEncodedString函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。