• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ PyMem_Free函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: PyErr_SetString

static PyObject *py_sorted_tree_items(PyObject *self, PyObject *entries)
{
	struct tree_item *qsort_entries = NULL;
	int num_entries, n = 0, i;
	PyObject *ret, *key, *value, *py_mode, *py_sha;
	Py_ssize_t pos = 0;

	if (!PyDict_Check(entries)) {
		PyErr_SetString(PyExc_TypeError, "Argument not a dictionary");
		goto error;
	}

	num_entries = PyDict_Size(entries);
	if (PyErr_Occurred())
		goto error;
	qsort_entries = PyMem_New(struct tree_item, num_entries);
	if (!qsort_entries) {
		PyErr_NoMemory();
		goto error;
	}

	while (PyDict_Next(entries, &pos, &key, &value)) {
		if (!PyString_Check(key)) {
			PyErr_SetString(PyExc_TypeError, "Name is not a string");
			goto error;
		}

		if (PyTuple_Size(value) != 2) {
			PyErr_SetString(PyExc_ValueError, "Tuple has invalid size");
			goto error;
		}

		py_mode = PyTuple_GET_ITEM(value, 0);
		if (!PyInt_Check(py_mode)) {
			PyErr_SetString(PyExc_TypeError, "Mode is not an integral type");
			goto error;
		}

		py_sha = PyTuple_GET_ITEM(value, 1);
		if (!PyString_Check(py_sha)) {
			PyErr_SetString(PyExc_TypeError, "SHA is not a string");
			goto error;
		}
		qsort_entries[n].name = PyString_AS_STRING(key);
		qsort_entries[n].mode = PyInt_AS_LONG(py_mode);

		qsort_entries[n].tuple = PyObject_CallFunctionObjArgs(
				tree_entry_cls, key, py_mode, py_sha, NULL);
		if (qsort_entries[n].tuple == NULL)
			goto error;
		n++;
	}

	qsort(qsort_entries, num_entries, sizeof(struct tree_item), cmp_tree_item);

	ret = PyList_New(num_entries);
	if (ret == NULL) {
		PyErr_NoMemory();
		goto error;
	}

	for (i = 0; i < num_entries; i++) {
		PyList_SET_ITEM(ret, i, qsort_entries[i].tuple);
	}
	PyMem_Free(qsort_entries);
	return ret;

error:
	for (i = 0; i < n; i++) {
		Py_XDECREF(qsort_entries[i].tuple);
	}
	PyMem_Free(qsort_entries);
	return NULL;
}
开发者ID:dmgctrl,项目名称:dulwich,代码行数:74,代码来源:_objects.c


示例2: DoPyCommand

/*
 * External interface
 */
    static void
DoPyCommand(const char *cmd, rangeinitializer init_range, runner run, void *arg)
{
#ifndef PY_CAN_RECURSE
    static int		recursive = 0;
#endif
#if defined(MACOS) && !defined(MACOS_X_UNIX)
    GrafPtr		oldPort;
#endif
#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
    char		*saved_locale;
#endif
#ifdef PY_CAN_RECURSE
    PyGILState_STATE	pygilstate;
#endif

#ifndef PY_CAN_RECURSE
    if (recursive)
    {
	EMSG(_("E659: Cannot invoke Python recursively"));
	return;
    }
    ++recursive;
#endif

#if defined(MACOS) && !defined(MACOS_X_UNIX)
    GetPort(&oldPort);
    /* Check if the Python library is available */
    if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
	goto theend;
#endif
    if (Python_Init())
	goto theend;

    init_range(arg);

    Python_Release_Vim();	    /* leave vim */

#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
    /* Python only works properly when the LC_NUMERIC locale is "C". */
    saved_locale = setlocale(LC_NUMERIC, NULL);
    if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
	saved_locale = NULL;
    else
    {
	/* Need to make a copy, value may change when setting new locale. */
	saved_locale = (char *) PY_STRSAVE(saved_locale);
	(void)setlocale(LC_NUMERIC, "C");
    }
#endif

#ifdef PY_CAN_RECURSE
    pygilstate = PyGILState_Ensure();
#else
    Python_RestoreThread();	    /* enter python */
#endif

    run((char *) cmd, arg
#ifdef PY_CAN_RECURSE
	    , &pygilstate
#endif
	    );

#ifdef PY_CAN_RECURSE
    PyGILState_Release(pygilstate);
#else
    Python_SaveThread();	    /* leave python */
#endif

#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
    if (saved_locale != NULL)
    {
	(void)setlocale(LC_NUMERIC, saved_locale);
	PyMem_Free(saved_locale);
    }
#endif

    Python_Lock_Vim();		    /* enter vim */
    PythonIO_Flush();
#if defined(MACOS) && !defined(MACOS_X_UNIX)
    SetPort(oldPort);
#endif

theend:
#ifndef PY_CAN_RECURSE
    --recursive;
#endif
    return;
}
开发者ID:crazyunix,项目名称:macvim,代码行数:92,代码来源:if_python.c


示例3: generic_dealloc

static void			/* generic instance destruction */
generic_dealloc (PyObject *self)
{
  DEBUG_MESS(1, " *** generic_dealloc %p\n", (void *) self);
  PyMem_Free(self);
}
开发者ID:juhnowski,项目名称:FishingRod,代码行数:6,代码来源:odeiv_old.c


示例4: PyWinObject_FreeString

void PyWinObject_FreeString(WCHAR *str)
{
	PyMem_Free(str);
}
开发者ID:malrsrch,项目名称:pywin32,代码行数:4,代码来源:PyUnicode.cpp


示例5: QSyntaxHighlighter

SyntaxHighlighter::SyntaxHighlighter(QTextDocument* doc)
    : QSyntaxHighlighter(doc)
{
    PyObject* kwmod = PyImport_ImportModule("keyword");
    PyObject* kwlist = PyObject_GetAttrString(kwmod, "kwlist");

    QList<QString> keywords = {"input", "output", "title", "meta"};

    // Get all of Python's keywords and add them to a list.
    for (int i=0; i < PyList_Size(kwlist); ++i)
    {
        PyObject* kw = PyList_GetItem(kwlist, i);

        wchar_t* w = PyUnicode_AsWideCharString(kw, NULL);
        keywords << QString::fromWCharArray(w);
        PyMem_Free(w);
    }

    Py_DECREF(kwlist);
    Py_DECREF(kwmod);

    // Make rules for all the Python keywords.
    QTextCharFormat kw_format;
    kw_format.setForeground(Colors::green);
    for (auto k : keywords)
    {
        rules << QPair<QRegularExpression, QTextCharFormat>(
                QRegularExpression("\\b" + k + "\\b"),
                kw_format);
    }

    QTextCharFormat quote_format;
    quote_format.setForeground(Colors::brown);
    rules << QPair<QRegularExpression, QTextCharFormat>(
            QRegularExpression("\\\".*\\\""), quote_format);
    rules << QPair<QRegularExpression, QTextCharFormat>(
            QRegularExpression("\\'.*\\'"), quote_format);

    // String that can be prepended to a regex to make it detect negative
    // numbers (but not subtraction).  Note that a closing parenthesis is
    // needed and the desired number is the last match group.
    QString neg = "(^|\\*\\*|[(+\\-=*\\/,\\[])([+\\-\\s]*";

    QTextCharFormat int_format;
    int_format.setForeground(Colors::orange);
    rules << QPair<QRegularExpression, QTextCharFormat>(
            QRegularExpression(neg + "\\b\\d+\\b)"), int_format);

    QTextCharFormat float_format;
    float_format.setForeground(Colors::yellow);
    rules << QPair<QRegularExpression, QTextCharFormat>(
            QRegularExpression(neg + "\\b\\d+\\.\\d*)"), float_format);
    rules << QPair<QRegularExpression, QTextCharFormat>(
            QRegularExpression(neg + "\\b\\d+\\.\\d*e\\d+)"), float_format);
    rules << QPair<QRegularExpression, QTextCharFormat>(
            QRegularExpression(neg + "\\b\\d+e\\d+)"), float_format);

    QTextCharFormat comment_format;
    comment_format.setForeground(Colors::base03);

    rules << QPair<QRegularExpression, QTextCharFormat>(
            QRegularExpression("#.*"), comment_format);
}
开发者ID:PhE,项目名称:antimony,代码行数:63,代码来源:syntax.cpp


示例6: format_complex_internal


//.........这里部分代码省略.........
    }

    /* Determine if we have any "remainder" (after the digits, might include
       decimal or exponent or both (or neither)) */
    parse_number(re_unicode_tmp, i_re, i_re + n_re_digits,
                 &n_re_remainder, &re_has_decimal);
    parse_number(im_unicode_tmp, i_im, i_im + n_im_digits,
                 &n_im_remainder, &im_has_decimal);

    /* Determine the grouping, separator, and decimal point, if any. */
    if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
                        (format->thousands_separators ?
                         LT_DEFAULT_LOCALE :
                         LT_NO_LOCALE),
                        &locale) == -1)
        goto done;

    /* Turn off any padding. We'll do it later after we've composed
       the numbers without padding. */
    tmp_format.fill_char = '\0';
    tmp_format.align = '<';
    tmp_format.width = -1;

    /* Calculate how much memory we'll need. */
    n_re_total = calc_number_widths(&re_spec, 0, re_sign_char, re_unicode_tmp,
                                    i_re, i_re + n_re_digits, n_re_remainder,
                                    re_has_decimal, &locale, &tmp_format,
                                    &maxchar);

    /* Same formatting, but always include a sign, unless the real part is
     * going to be omitted, in which case we use whatever sign convention was
     * requested by the original format. */
    if (!skip_re)
        tmp_format.sign = '+';
    n_im_total = calc_number_widths(&im_spec, 0, im_sign_char, im_unicode_tmp,
                                    i_im, i_im + n_im_digits, n_im_remainder,
                                    im_has_decimal, &locale, &tmp_format,
                                    &maxchar);

    if (skip_re)
        n_re_total = 0;

    /* Add 1 for the 'j', and optionally 2 for parens. */
    calc_padding(n_re_total + n_im_total + 1 + add_parens * 2,
                 format->width, format->align, &lpad, &rpad, &total);

    if (lpad || rpad)
        maxchar = Py_MAX(maxchar, format->fill_char);

    if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1)
        goto done;
    rkind = writer->kind;
    rdata = writer->data;

    /* Populate the memory. First, the padding. */
    result = fill_padding(writer,
                          n_re_total + n_im_total + 1 + add_parens * 2,
                          format->fill_char, lpad, rpad);
    if (result == -1)
        goto done;

    if (add_parens) {
        PyUnicode_WRITE(rkind, rdata, writer->pos, '(');
        writer->pos++;
    }

    if (!skip_re) {
        result = fill_number(writer, &re_spec,
                             re_unicode_tmp, i_re, i_re + n_re_digits,
                             NULL, 0,
                             0,
                             &locale, 0);
        if (result == -1)
            goto done;
    }
    result = fill_number(writer, &im_spec,
                         im_unicode_tmp, i_im, i_im + n_im_digits,
                         NULL, 0,
                         0,
                         &locale, 0);
    if (result == -1)
        goto done;
    PyUnicode_WRITE(rkind, rdata, writer->pos, 'j');
    writer->pos++;

    if (add_parens) {
        PyUnicode_WRITE(rkind, rdata, writer->pos, ')');
        writer->pos++;
    }

    writer->pos += rpad;

done:
    PyMem_Free(re_buf);
    PyMem_Free(im_buf);
    Py_XDECREF(re_unicode_tmp);
    Py_XDECREF(im_unicode_tmp);
    free_locale_info(&locale);
    return result;
}
开发者ID:TruckHacking,项目名称:J1939Python,代码行数:101,代码来源:formatter_unicode.c


示例7: format_float_internal

/* much of this is taken from unicodeobject.c */
static int
format_float_internal(PyObject *value,
                      const InternalFormatSpec *format,
                      _PyUnicodeWriter *writer)
{
    char *buf = NULL;       /* buffer returned from PyOS_double_to_string */
    Py_ssize_t n_digits;
    Py_ssize_t n_remainder;
    Py_ssize_t n_total;
    int has_decimal;
    double val;
    int precision, default_precision = 6;
    Py_UCS4 type = format->type;
    int add_pct = 0;
    Py_ssize_t index;
    NumberFieldWidths spec;
    int flags = 0;
    int result = -1;
    Py_UCS4 maxchar = 127;
    Py_UCS4 sign_char = '\0';
    int float_type; /* Used to see if we have a nan, inf, or regular float. */
    PyObject *unicode_tmp = NULL;

    /* Locale settings, either from the actual locale or
       from a hard-code pseudo-locale */
    LocaleInfo locale = STATIC_LOCALE_INFO_INIT;

    if (format->precision > INT_MAX) {
        PyErr_SetString(PyExc_ValueError, "precision too big");
        goto done;
    }
    precision = (int)format->precision;

    if (format->alternate)
        flags |= Py_DTSF_ALT;

    if (type == '\0') {
        /* Omitted type specifier.  Behaves in the same way as repr(x)
           and str(x) if no precision is given, else like 'g', but with
           at least one digit after the decimal point. */
        flags |= Py_DTSF_ADD_DOT_0;
        type = 'r';
        default_precision = 0;
    }

    if (type == 'n')
        /* 'n' is the same as 'g', except for the locale used to
           format the result. We take care of that later. */
        type = 'g';

    val = PyFloat_AsDouble(value);
    if (val == -1.0 && PyErr_Occurred())
        goto done;

    if (type == '%') {
        type = 'f';
        val *= 100;
        add_pct = 1;
    }

    if (precision < 0)
        precision = default_precision;
    else if (type == 'r')
        type = 'g';

    /* Cast "type", because if we're in unicode we need to pass an
       8-bit char. This is safe, because we've restricted what "type"
       can be. */
    buf = PyOS_double_to_string(val, (char)type, precision, flags,
                                &float_type);
    if (buf == NULL)
        goto done;
    n_digits = strlen(buf);

    if (add_pct) {
        /* We know that buf has a trailing zero (since we just called
           strlen() on it), and we don't use that fact any more. So we
           can just write over the trailing zero. */
        buf[n_digits] = '%';
        n_digits += 1;
    }

    if (format->sign != '+' && format->sign != ' '
        && format->width == -1
        && format->type != 'n'
        && !format->thousands_separators)
    {
        /* Fast path */
        result = _PyUnicodeWriter_WriteASCIIString(writer, buf, n_digits);
        PyMem_Free(buf);
        return result;
    }

    /* Since there is no unicode version of PyOS_double_to_string,
       just use the 8 bit version and then convert to unicode. */
    unicode_tmp = _PyUnicode_FromASCII(buf, n_digits);
    PyMem_Free(buf);
    if (unicode_tmp == NULL)
        goto done;
//.........这里部分代码省略.........
开发者ID:TruckHacking,项目名称:J1939Python,代码行数:101,代码来源:formatter_unicode.c


示例8: NumberVar_GetFormatAndTextFromDecimal

//-----------------------------------------------------------------------------
// NumberVar_GetFormatAndTextFromDecimal()
//   Return the number format and text to use for the Decimal object.
//-----------------------------------------------------------------------------
static int NumberVar_GetFormatAndTextFromDecimal(
    PyObject *tupleValue,               // decimal as_tuple() value
    PyObject **textObj,                 // text string for conversion
    PyObject **formatObj)               // format for conversion
{
    long numDigits, scale, i, sign, length, digit;
    char *textValue, *format, *textPtr, *formatPtr;
    PyObject *digits;

    // acquire basic information from the value tuple
    sign = PyInt_AsLong(PyTuple_GET_ITEM(tupleValue, 0));
    if (PyErr_Occurred())
        return -1;
    digits = PyTuple_GET_ITEM(tupleValue, 1);
    scale = PyInt_AsLong(PyTuple_GET_ITEM(tupleValue, 2));
    if (PyErr_Occurred())
        return -1;
    numDigits = PyTuple_GET_SIZE(digits);

    // allocate memory for the string and format to use in conversion
    length = numDigits + abs(scale) + 3;
    textValue = textPtr = PyMem_Malloc(length);
    if (!textValue) {
        PyErr_NoMemory();
        return -1;
    }
    format = formatPtr = PyMem_Malloc(length);
    if (!format) {
        PyMem_Free(textValue);
        PyErr_NoMemory();
        return -1;
    }

    // populate the string and format
    if (sign)
        *textPtr++ = '-';
    for (i = 0; i < numDigits + scale; i++) {
        *formatPtr++ = '9';
        if (i < numDigits) {
            digit = PyInt_AsLong(PyTuple_GetItem(digits, i));
            if (PyErr_Occurred()) {
                PyMem_Free(textValue);
                return -1;
            }
        }
        else digit = 0;
        *textPtr++ = '0' + (char) digit;
    }
    if (scale < 0) {
        *formatPtr++ = 'D';
        *textPtr++ = '.';
        for (i = scale; i < 0; i++) {
            *formatPtr++ = '9';
            if (numDigits + i < 0)
                digit = 0;
            else {
                digit = PyInt_AsLong(PyTuple_GetItem(digits, numDigits + i));
                if (PyErr_Occurred()) {
                    PyMem_Free(textValue);
                    return -1;
                }
            }
            *textPtr++ = '0' + (char) digit;
        }
    }
    *formatPtr = '\0';
    *textPtr = '\0';
    *textObj = cxString_FromAscii(textValue);
    PyMem_Free(textValue);
    if (!*textObj) {
        PyMem_Free(format);
        return -1;
    }
    *formatObj = cxString_FromAscii(format);
    PyMem_Free(format);
    if (!*formatObj) {
        Py_DECREF(*textObj);
        return -1;
    }

    return 0;
}
开发者ID:15580056814,项目名称:hue,代码行数:86,代码来源:NumberVar.c


示例9: get_device_ancestors

PSP_DEVICE_INTERFACE_DETAIL_DATA
get_device_ancestors(HDEVINFO hDevInfo, DWORD index, PyObject *candidates, BOOL *iterate, BOOL ddebug) {
    SP_DEVICE_INTERFACE_DATA            interfaceData;
    SP_DEVINFO_DATA						devInfoData;
    BOOL                                status;
    PSP_DEVICE_INTERFACE_DETAIL_DATA    interfaceDetailData;
    DWORD                               interfaceDetailDataSize,
                                        reqSize;
    DEVINST                             parent, pos;
    wchar_t                             temp[BUFSIZE];
    int                                 i;
    PyObject                            *devid;

    interfaceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);
    devInfoData.cbSize   = sizeof (SP_DEVINFO_DATA);

    status = SetupDiEnumDeviceInterfaces (
                hDevInfo,               // Interface Device Info handle
                NULL,                   // Device Info data
                (LPGUID)&GUID_DEVINTERFACE_VOLUME, // Interface registered by driver
                index,                  // Member
                &interfaceData          // Device Interface Data
                );
    if ( status == FALSE ) {
        *iterate = FALSE;
        return NULL;
    }
    SetupDiGetDeviceInterfaceDetail (
                hDevInfo,           // Interface Device info handle
                &interfaceData,     // Interface data for the event class
                NULL,               // Checking for buffer size
                0,                  // Checking for buffer size
                &reqSize,           // Buffer size required to get the detail data
                NULL                // Checking for buffer size
    );

    interfaceDetailDataSize = reqSize;
    interfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)PyMem_Malloc(interfaceDetailDataSize+50);
    if ( interfaceDetailData == NULL ) {
        PyErr_NoMemory();
        return NULL;
    }
    interfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);
    devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

    status = SetupDiGetDeviceInterfaceDetail (
                  hDevInfo,                 // Interface Device info handle
                  &interfaceData,           // Interface data for the event class
                  interfaceDetailData,      // Interface detail data
                  interfaceDetailDataSize,  // Interface detail data size
                  &reqSize,                 // Buffer size required to get the detail data
                  &devInfoData);            // Interface device info
    if (ddebug) printf("Getting ancestors\n"); fflush(stdout);

    if ( status == FALSE ) {PyErr_SetFromWindowsErr(0); PyMem_Free(interfaceDetailData); return NULL;}

    pos = devInfoData.DevInst;

    for(i = 0; i < 10; i++) {
        // Get the device instance of parent.
        if (CM_Get_Parent(&parent, pos, 0) != CR_SUCCESS) break;
        if (CM_Get_Device_ID(parent, temp, BUFSIZE, 0) == CR_SUCCESS) {
            if (ddebug) console_out(L"device id: %s\n", temp);
            devid = PyUnicode_FromWideChar(temp, wcslen(temp));
            if (devid) {
                PyList_Append(candidates, devid);
                Py_DECREF(devid);
            }
        }
        pos = parent;
    }

    return interfaceDetailData;
}
开发者ID:yeyanchao,项目名称:calibre,代码行数:74,代码来源:winutil.c


示例10: pyfshfs_file_object_io_handle_initialize

/* Creates a file object IO handle
 * Make sure the value file_object_io_handle is referencing, is set to NULL
 * Returns 1 if successful or -1 on error
 */
int pyfshfs_file_object_io_handle_initialize(
     pyfshfs_file_object_io_handle_t **file_object_io_handle,
     PyObject *file_object,
     libcerror_error_t **error )
{
	static char *function = "pyfshfs_file_object_io_handle_initialize";

	if( file_object_io_handle == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid file object IO handle.",
		 function );

		return( -1 );
	}
	if( *file_object_io_handle != NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET,
		 "%s: invalid file object IO handle value already set.",
		 function );

		return( -1 );
	}
	if( file_object == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid file object.",
		 function );

		return( -1 );
	}
	*file_object_io_handle = (pyfshfs_file_object_io_handle_t *) PyMem_Malloc(
	                                                              sizeof( pyfshfs_file_object_io_handle_t ) );

	if( *file_object_io_handle == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
		 "%s: unable to create file object IO handle.",
		 function );

		goto on_error;
	}
	if( memory_set(
	     *file_object_io_handle,
	     0,
	     sizeof( pyfshfs_file_object_io_handle_t ) ) == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_SET_FAILED,
		 "%s: unable to clear file object IO handle.",
		 function );

		goto on_error;
	}
	( *file_object_io_handle )->file_object = file_object;

	Py_IncRef(
	 ( *file_object_io_handle )->file_object );

	return( 1 );

on_error:
	if( *file_object_io_handle != NULL )
	{
		PyMem_Free(
		 *file_object_io_handle );

		*file_object_io_handle = NULL;
	}
	return( -1 );
}
开发者ID:roox,项目名称:libfshfs,代码行数:89,代码来源:pyfshfs_file_object_io_handle.c


示例11: PyErr_Format


//.........这里部分代码省略.........

	if( ( number_of_filenames <= 0 )
	 || ( number_of_filenames > (int) UINT16_MAX ) )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid number of files.",
		 function );

		goto on_error;
	}
	filenames = (char **) PyMem_Malloc(
	                       sizeof( char * ) * number_of_filenames );

	if( filenames == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to create filenames.",
		 function );

		goto on_error;
	}
	if( memory_set(
	     filenames,
	     0,
	     sizeof( char * ) * number_of_filenames ) == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to clear filenames.",
		 function );

		PyMem_Free(
		 filenames );

		return( NULL );
	}
	for( filename_index = 0;
	     filename_index < number_of_filenames;
	     filename_index++ )
	{
		string_object = PySequence_GetItem(
		                 sequence_object,
		                 filename_index );

		filename_length = PyString_Size(
		                   string_object );

		filenames[ filename_index ] = (char *) PyMem_Malloc(
		                                        sizeof( char ) * ( filename_length + 1 ) );

		if( filenames[ filename_index ] == NULL )
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to create filename: %d.",
			 function,
			 filename_index );

			goto on_error;
		}
		if( libcstring_narrow_string_copy(
		     filenames[ filename_index ],
		     PyString_AsString(
		      string_object ),
开发者ID:aoighost,项目名称:libewf,代码行数:67,代码来源:pyewf_handle.c


示例12: Z_set

static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
	if (value == Py_None) {
		*(wchar_t **)ptr = NULL;
		Py_INCREF(value);
		return value;
	}
	if (PyString_Check(value)) {
		value = PyUnicode_FromEncodedObject(value,
						    conversion_mode_encoding,
						    conversion_mode_errors);
		if (!value)
			return NULL;
	} else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
		*(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
#else
		*(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
#endif
		Py_INCREF(Py_None);
		return Py_None;
	} else if (!PyUnicode_Check(value)) {
		PyErr_Format(PyExc_TypeError,
			     "unicode string or integer address expected instead of %s instance",
			     value->ob_type->tp_name);
		return NULL;
	} else
		Py_INCREF(value);
#ifdef HAVE_USABLE_WCHAR_T
	/* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
	   type.  So we can copy directly.  Hm, are unicode objects always NUL
	   terminated in Python, internally?
	 */
	*(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
	return value;
#else
	{
		/* We must create a wchar_t* buffer from the unicode object,
		   and keep it alive */
		PyObject *keep;
		wchar_t *buffer;

		int size = PyUnicode_GET_SIZE(value);
		size += 1; /* terminating NUL */
		size *= sizeof(wchar_t);
		buffer = (wchar_t *)PyMem_Malloc(size);
		if (!buffer) {
			Py_DECREF(value);
			return PyErr_NoMemory();
		}
		memset(buffer, 0, size);
		keep = PyCObject_FromVoidPtr(buffer, PyMem_Free);
		if (!keep) {
			Py_DECREF(value);
			PyMem_Free(buffer);
			return NULL;
		}
		*(wchar_t **)ptr = (wchar_t *)buffer;
		if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
					       buffer, PyUnicode_GET_SIZE(value))) {
			Py_DECREF(value);
			Py_DECREF(keep);
			return NULL;
		}
		Py_DECREF(value);
		return keep;
	}
#endif
}
开发者ID:1310701102,项目名称:sl4a,代码行数:70,代码来源:cfield.c


示例13: Py_FrozenMain

int
Py_FrozenMain(int argc, char **argv)
{
    char *p;
    int i, n, sts;
    int inspect = 0;
    int unbuffered = 0;
    char *oldloc;
    wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc);
    /* We need a second copies, as Python might modify the first one. */
    wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc);

    Py_FrozenFlag = 1; /* Suppress errors from getpath.c */

    if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
        inspect = 1;
    if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
        unbuffered = 1;

    if (unbuffered) {
        setbuf(stdin, (char *)NULL);
        setbuf(stdout, (char *)NULL);
        setbuf(stderr, (char *)NULL);
    }

    if (!argv_copy) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }

    oldloc = setlocale(LC_ALL, NULL);
    setlocale(LC_ALL, "");
    for (i = 0; i < argc; i++) {
#ifdef HAVE_BROKEN_MBSTOWCS
        size_t argsize = strlen(argv[i]);
#else
        size_t argsize = mbstowcs(NULL, argv[i], 0);
#endif
        size_t count;
        if (argsize == (size_t)-1) {
            fprintf(stderr, "Could not convert argument %d to string\n", i);
            return 1;
        }
        argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t));
        argv_copy2[i] = argv_copy[i];
        if (!argv_copy[i]) {
            fprintf(stderr, "out of memory\n");
            return 1;
        }
        count = mbstowcs(argv_copy[i], argv[i], argsize+1);
        if (count == (size_t)-1) {
            fprintf(stderr, "Could not convert argument %d to string\n", i);
            return 1;
        }
    }
    setlocale(LC_ALL, oldloc);

#ifdef MS_WINDOWS
    PyInitFrozenExtensions();
#endif /* MS_WINDOWS */
    Py_SetProgramName(argv_copy[0]);
    Py_Initialize();
#ifdef MS_WINDOWS
    PyWinFreeze_ExeInit();
#endif

    if (Py_VerboseFlag)
        fprintf(stderr, "Python %s\n%s\n",
            Py_GetVersion(), Py_GetCopyright());

    PySys_SetArgv(argc, argv_copy);

    n = PyImport_ImportFrozenModule("__main__");
    if (n == 0)
        Py_FatalError("__main__ not frozen");
    if (n < 0) {
        PyErr_Print();
        sts = 1;
    }
    else
        sts = 0;

    if (inspect && isatty((int)fileno(stdin)))
        sts = PyRun_AnyFile(stdin, "<stdin>") != 0;

#ifdef MS_WINDOWS
    PyWinFreeze_ExeTerm();
#endif
    Py_Finalize();
    for (i = 0; i < argc; i++) {
        PyMem_Free(argv_copy2[i]);
    }
    PyMem_Free(argv_copy);
    PyMem_Free(argv_copy2);
    return sts;
}
开发者ID:524777134,项目名称:cpython,代码行数:96,代码来源:frozenmain.c


示例14: fortran_doc

static PyObject *
fortran_doc(FortranDataDef def)
{
    char *buf, *p;
    PyObject *s = NULL;
    Py_ssize_t n, origsize, size = 100;

    if (def.doc != NULL) {
        size += strlen(def.doc);
    }
    origsize = size;
    buf = p = (char *)PyMem_Malloc(size);
    if (buf == NULL) {
        return PyErr_NoMemory();
    }

    if (def.rank == -1) {
        if (def.doc) {
            n = strlen(def.doc);
            if (n > size) {
                goto fail;
            }
            memcpy(p, def.doc, n);
            p += n;
            size -= n;
        }
        else {
            n = PyOS_snprintf(p, size, "%s - no docs available", def.name);
            if (n < 0 || n >= size) {
                goto fail;
            }
            p += n;
            size -= n;
        }
    }
    else {
        PyArray_Descr *d = PyArray_DescrFromType(def.type);
        n = PyOS_snprintf(p, size, "'%c'-", d->type);
        Py_DECREF(d);
        if (n < 0 || n >= size) {
            goto fail;
        }
        p += n;
        size -= n;

        if (def.data == NULL) {
            n = format_def(p, size, def) == -1;
            if (n < 0) {
                goto fail;
            }
            p += n;
            size -= n;
        }
        else if (def.rank > 0) {
            n = format_def(p, size, def);
            if (n < 0) {
                goto fail;
            }
            p += n;
            size -= n;
        }
        else {
            n = strlen("scalar");
            if (size < n) {
                goto fail;
            }
            memcpy(p, "scalar", n);
            p += n;
            size -= n;
        }
    }
    if (size <= 1) {
        goto fail;
    }
    *p++ = '\n';
    size--;

    /* p now points one beyond the last character of the string in buf */
#if PY_VERSION_HEX >= 0x03000000
    s = PyUnicode_FromStringAndSize(buf, p - buf);
#else
    s = PyString_FromStringAndSize(buf, p - buf);
#endif

    PyMem_Free(buf);
    return s;

 fail:
    fprintf(stderr, "fortranobject.c: fortran_doc: len(p)=%zd>%zd=size:"
                    " too long docstring required, increase size\n",
            p - buf, origsize);
    PyMem_Free(buf);
    return NULL;
}
开发者ID:7924102,项目名称:numpy,代码行数:94,代码来源:fortranobject.c


示例15: BPY_BM_CHECK_OBJ

static PyObject *bpy_bm_utils_face_split(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
	static const char *kwlist[] = {"face", "vert_a", "vert_b",
	                               "coords", "use_exist", "example", NULL};

	BPy_BMFace *py_face;
	BPy_BMVert *py_vert_a;
	BPy_BMVert *py_vert_b;

	/* optional */
	PyObject *py_coords = NULL;
	bool edge_exists = true;
	BPy_BMEdge *py_edge_example = NULL;

	float *coords;
	int ncoords = 0;

	BMesh *bm;
	BMFace *f_new = NULL;
	BMLoop *l_new = NULL;
	BMLoop *l_a, *l_b;

	if (!PyArg_ParseTupleAndKeywords(
	        args, kw,
	        "O!O!O!|OO&O!:face_split", (char **)kwlist,
	        &BPy_BMFace_Type, &py_face,
	        &BPy_BMVert_Type, &py_vert_a,
	        &BPy_BMVert_Type, &py_vert_b,
	        &py_coords,
	        PyC_ParseBool, &edge_exists,
	        &BPy_BMEdge_Type, &py_edge_example))
	{
		return NULL;
	}

	BPY_BM_CHECK_OBJ(py_face);
	BPY_BM_CHECK_OBJ(py_vert_a);
	BPY_BM_CHECK_OBJ(py_vert_b);

	if (py_edge_example) {
		BPY_BM_CHECK_OBJ(py_edge_example);
	}

	/* this doubles for checking that the verts are in the same mesh */
	if ((l_a = BM_face_vert_share_loop(py_face->f, py_vert_a->v)) &&
	    (l_b = BM_face_vert_share_loop(py_face->f, py_vert_b->v)))
	{
		/* pass */
	}
	else {
		PyErr_SetString(PyExc_ValueError,
		                "face_split(...): one of the verts passed is not found in the face");
		return NULL;
	}

	if (py_vert_a->v == py_vert_b->v) {
		PyErr_SetString(PyExc_ValueError,
		                "face_split(...): vert arguments must differ");
		return NULL;
	}

	if (py_coords) {
		ncoords = mathutils_array_parse_alloc_v(&coords, 3, py_coords, "face_split(...): ");
		if (ncoords == -1) {
			return NULL;
		}
	}
	else {
		if (BM_loop_is_adjacent(l_a, l_b)) {
			PyErr_SetString(PyExc_ValueError,
			                "face_split(...): verts are adjacent in the face");
			return NULL;
		}
	}

	/* --- main function body --- */
	bm = py_face->bm;

	if (ncoords) {
		f_new = BM_face_split_n(bm, py_face->f,
		                        l_a, l_b,
		                        (float (*)[3])coords, ncoords,
		                        &l_new, py_edge_example ? py_edge_example->e : NULL);
		PyMem_Free(coords);
	}
	else {
		f_new = BM_face_split(bm, py_face->f,
		                      l_a, l_b,
		                      &l_new, py_edge_example ? py_edge_example->e : NULL, edge_exists);
	}

	if (f_new && l_new) {
		PyObject *ret = PyTuple_New(2);
		PyTuple_SET_ITEMS(ret,
		        BPy_BMFace_CreatePyObject(bm, f_new),
		        BPy_BMLoop_CreatePyObject(bm, l_new));
		return ret;
	}
	else {
		PyErr_SetString(PyExc_ValueError,
//.........这里部分代码省略.........
开发者ID:Ichthyostega,项目名称:blender,代码行数:101,代码来源:bmesh_py_utils.c


示例16: winutil_get_removable_drives

static PyObject *
winutil_get_removable_drives(PyObject *self, PyObject *args) {
    HDEVINFO hDevInfo;
	BOOL  iterate = TRUE, ddebug = FALSE;
	PSP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetailData;
    DWORD i;
    unsigned int j, length;
    WCHAR volume[BUFSIZE];
    struct tagDrives g_drives[MAX_DRIVES];
    PyObject *volumes, *key, *candidates, *pdebug = Py_False, *temp;

    if (!PyArg_ParseTuple(args, "|O", &pdebug)) {
    	return NULL;
    }

    // Find all removable drives
    for (j = 0; j < MAX_DRIVES; j++) g_drives[j].letter = 0;
    if (!get_all_removable_disks(g_drives)) return NULL;

    volumes = PyDict_New();
    if (volumes == NULL) return PyErr_NoMemory();
    ddebug = PyObject_IsTrue(pdebug);

    hDevInfo = create_device_info_set((LPGUID)&GUID_DEVINTERFACE_VOLUME,
                            NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
    if (hDevInfo == INVALID_HANDLE_VALUE) { Py_DECREF(volumes); return NULL; }

    // Enumerate through the set
    for (i=0; iterate; i++) {
        candidates = PyList_New(0);
        if (candidates == NULL) { Py_DECREF(volumes); return PyErr_NoMemory();}

        interfaceDetailData = get_device_ancestors(hDevInfo, i, candidates, &iterate, ddebug);
        if (interfaceDetailData == NULL) {
            PyErr_Print(); 
            Py_DECREF(candidates); candidates = NULL; 
            continue;
        }

        length = wcslen(interfaceDetailData->DevicePath);
        interfaceDetailData->DevicePath[length] = L'\\';
        interfaceDetailData->DevicePath[length+1] = 0;

        if (ddebug) console_out(L"Device path: %s\n", interfaceDetailData->DevicePath);
        // On Vista+ DevicePath contains the information we need.
        temp = PyUnicode_FromWideChar(interfaceDetailData->DevicePath, length);
        if (temp == NULL) return PyErr_NoMemory();
        PyList_Append(candidates, temp);
        Py_DECREF(temp);
        if(GetVolumeNameForVolumeMountPointW(interfaceDetailData->DevicePath, volume, BUFSIZE)) {
            if (ddebug) console_out(L"Volume: %s\n", volume);
            
            for(j = 0; j < MAX_DRIVES; j++) {
                if(g_drives[j].letter != 0 && wcscmp(g_drives[j].volume, volume)==0) {
                    if (ddebug) printf("Found drive: %c\n", (char)g_drives[j].letter); fflush(stdout);
                    key = PyBytes_FromFormat("%c", (char)g_drives[j].letter);
                    if (key == NULL) return PyErr_NoMemory();
                    PyDict_SetItem(volumes, key, candidates);
                    Py_DECREF(key); key = NULL;
                    break;
                }
            }

        }
        Py_XDECREF(candidates); candidates = NULL;
        PyMem_Free(interfaceDetailData);
    } //for

    SetupDiDestroyDeviceInfoList(hDevInfo);
    return volumes;
}
开发者ID:yeyanchao,项目名称:calibre,代码行数:71,代码来源:winutil.c


示例17: initstdio


//.........这里部分代码省略.........
            pythonioencoding = _PyMem_Strdup(pythonioencoding);
            if (pythonioencoding == NULL) {
                PyErr_NoMemory();
                goto error;
            }
            err = strchr(pythonioencoding, ':');
            if (err) {
                *err = '\0';
                err++;
                if (*err && !errors) {
                    errors = err;
                }
            }
            if (*pythonioencoding && !encoding) {
                encoding = pythonioencoding;
            }
        }
        if (!errors && !(pythonioencoding && *pythonioencoding)) {
            /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
               stdin and stdout use the surrogateescape error handler by
               default, instead of the strict error handler. */
            char *loc = setlocale(LC_CTYPE, NULL);
            if (loc != NULL && strcmp(loc, "C") == 0)
                errors = "surrogateescape";
        }
    }

    /* Set sys.stdin */
    fd = fileno(stdin);
    /* Under some conditions stdin, stdout and stderr may not be connected
     * and fileno() may point to an invalid file descriptor. For example
     * GUI apps don't have valid standard streams by default.
     */
    std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
    if (std == NULL)
        goto error;
    PySys_SetObject("__stdin__", std);
    _PySys_SetObjectId(&PyId_stdin, std);
    Py_DECREF(std);

    /* Set sys.stdout */
    fd = fileno(stdout);
    std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
    if (std == NULL)
        goto error;
    PySys_SetObject("__stdout__", std);
    _PySys_SetObjectId(&PyId_stdout, std);
    Py_DECREF(std);

#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
    /* Set sys.stderr, replaces the preliminary stderr */
    fd = fileno(stderr);
    std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
    if (std == NULL)
        goto error;

    /* Same as hack above, pre-import stderr's codec to avoid recursion
       when import.c tries to write to stderr in verbose mode. */
    encoding_attr = PyObject_GetAttrString(std, "encoding");
    if (encoding_attr != NULL) {
        const char * std_encoding;
        std_encoding = _PyUnicode_AsString(encoding_attr);
        if (std_encoding != NULL) {
            PyObject *codec_info = _PyCodec_Lookup(std_encoding);
            Py_XDECREF(codec_info);
        }
        Py_DECREF(encoding_attr);
    }
    PyErr_Clear();  /* Not a fatal error if codec isn't available */

    if (PySys_SetObject("__stderr__", std) < 0) {
        Py_DECREF(std);
        goto error;
    }
    if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
        Py_DECREF(std);
        goto error;
    }
    Py_DECREF(std);
#endif

    if (0) {
  error:
        status = -1;
    }

    /* We won't need them anymore. */
    if (_Py_StandardStreamEncoding) {
        PyMem_RawFree(_Py_StandardStreamEncoding);
        _Py_StandardStreamEncoding = NULL;
    }
    if (_Py_StandardStreamErrors) {
        PyMem_RawFree(_Py_StandardStreamErrors);
        _Py_StandardStreamErrors = NULL;
    }
    PyMem_Free(pythonioencoding);
    Py_XDECREF(bimod);
    Py_XDECREF(iomod);
    return status;
}
开发者ID:cherish3620,项目名称:cpython,代码行数:101,代码来源:pylifecycle.c


示例18: winutil_strftime

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ PyMem_RawFree函数代码示例发布时间:2022-05-30
下一篇:
C++ PyMac_PRECHECK函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap