static PyObject * cups_modelSort (PyObject *self, PyObject *args) { PyObject *Oa, *Ob, *a, *b; int len_a, len_b; size_t size_a, size_b; wchar_t *wca, *wcb; if (!PyArg_ParseTuple (args, "OO", &Oa, &Ob)) return NULL; a = PyUnicode_FromObject (Oa); b = PyUnicode_FromObject (Ob); if (a == NULL || b == NULL || !PyUnicode_Check (a) || !PyUnicode_Check (b)) { if (a) { Py_DECREF (a); } if (b) { Py_DECREF (b); } PyErr_SetString (PyExc_TypeError, "Unable to convert to Unicode"); return NULL; } len_a = 1 + PyUnicode_GetSize (a); size_a = len_a * sizeof (wchar_t); if ((size_a / sizeof (wchar_t)) != len_a) { Py_DECREF (a); Py_DECREF (b); PyErr_SetString (PyExc_RuntimeError, "String too long"); return NULL; } len_b = 1 + PyUnicode_GetSize (b); size_b = len_b * sizeof (wchar_t); if ((size_b / sizeof (wchar_t)) != len_b) { Py_DECREF (a); Py_DECREF (b); PyErr_SetString (PyExc_RuntimeError, "String too long"); return NULL; } wca = malloc (size_a); wcb = malloc (size_b); if (wca == NULL || wcb == NULL) { Py_DECREF (a); Py_DECREF (b); free (wca); free (wcb); PyErr_SetString (PyExc_RuntimeError, "Insufficient memory"); return NULL; } PyUnicode_AsWideChar ((PyUnicodeObject *) a, wca, size_a); PyUnicode_AsWideChar ((PyUnicodeObject *) b, wcb, size_b); Py_DECREF (a); Py_DECREF (b); return Py_BuildValue ("i", do_model_compare (wca, wcb)); }
// Collator.startswith {{{ static PyObject * icu_Collator_collation_order(icu_Collator *self, PyObject *args, PyObject *kwargs) { PyObject *a_; int32_t asz; int32_t actual_a; UChar *a; wchar_t *aw; UErrorCode status = U_ZERO_ERROR; UCollationElements *iter = NULL; int order = 0, len = -1; if (!PyArg_ParseTuple(args, "U", &a_)) return NULL; asz = (int32_t)PyUnicode_GetSize(a_); a = (UChar*)calloc(asz*4 + 2, sizeof(UChar)); aw = (wchar_t*)calloc(asz*4 + 2, sizeof(wchar_t)); if (a == NULL || aw == NULL ) return PyErr_NoMemory(); actual_a = (int32_t)PyUnicode_AsWideChar((PyUnicodeObject*)a_, aw, asz*4+1); if (actual_a > -1) { u_strFromWCS(a, asz*4 + 1, &actual_a, aw, -1, &status); iter = ucol_openElements(self->collator, a, actual_a, &status); if (iter != NULL && U_SUCCESS(status)) { order = ucol_next(iter, &status); len = ucol_getOffset(iter); ucol_closeElements(iter); iter = NULL; } } free(a); free(aw); return Py_BuildValue("ii", order, len); } // }}}
int should_trace_module(PyObject *module_str) { int i, len, found; PyObject *item; #ifndef IS_PY3K char *filter, *module; #endif if (NULL == filter_modules) { return TRUE; } #ifndef IS_PY3K module = PyString_AsString(module_str); #endif found = FALSE; len = PyList_Size(filter_modules); for (i = 0; i < len && FALSE == found; i++) { item = PyList_GetItem(filter_modules, i); #ifdef IS_PY3K found = PyUnicode_Find(module_str, item, 0, PyUnicode_GetSize(item), 1) >= 0 ? TRUE : FALSE ; #else filter = PyString_AsString(item); found = strncmp(module, filter, strlen(filter)) == 0 ? TRUE : FALSE; #endif } return found; }
PYTHON_METHOD_DEFINITION(ptGUIControlMultiLineEdit, insertStringW, args) { PyObject* textObj; if (!PyArg_ParseTuple(args, "O", &textObj)) { PyErr_SetString(PyExc_TypeError, "insertStringW expects a unicode string"); PYTHON_RETURN_ERROR; } if (PyUnicode_Check(textObj)) { int strLen = PyUnicode_GetSize(textObj); wchar_t* temp = new wchar_t[strLen + 1]; PyUnicode_AsWideChar((PyUnicodeObject*)textObj, temp, strLen); temp[strLen] = L'\0'; self->fThis->InsertStringW(temp); delete [] temp; PYTHON_RETURN_NONE; } else if (PyString_Check(textObj)) { // we'll allow this, just in case something goes weird char* temp = PyString_AsString(textObj); self->fThis->InsertString(temp); PYTHON_RETURN_NONE; } else { PyErr_SetString(PyExc_TypeError, "insertStringW expects a unicode string"); PYTHON_RETURN_ERROR; } }
static int AE_GetCFStringRef(PyObject *v, CFStringRef *p_itself) { if (v == Py_None) { *p_itself = NULL; return 1; } if (PyBytes_Check(v)) { char *cStr; if (!PyArg_Parse(v, "es", "ascii", &cStr)) return 0; *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII); PyMem_Free(cStr); return 1; } if (PyUnicode_Check(v)) { #ifdef Py_UNICODE_WIDE CFIndex size = PyUnicode_GET_DATA_SIZE(v); UTF32Char *unichars = PyUnicode_AsUnicode(v); *p_itself = CFStringCreateWithBytes((CFAllocatorRef)NULL, unichars, size, kCFStringEncodingUTF32, // 10.4+ false); // ? #else CFIndex size = PyUnicode_GetSize(v); UniChar *unichars = PyUnicode_AsUnicode(v); if (!unichars) return 0; *p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size); #endif return 1; } PyErr_SetString(PyExc_TypeError, "str/unicode required"); return 0; }
BlockLocator * BlockLocator_new(PyUnicodeObject* codestr) { BlockLocator *self; #ifdef DEBUG fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); #endif self = PyMem_New(BlockLocator, 1); if (self) { memset(self, 0, sizeof(BlockLocator)); Py_INCREF(codestr); self->py_codestr = codestr; self->codestr = PyUnicode_AS_UNICODE(codestr); self->codestr_sz = PyUnicode_GetSize((PyObject*)codestr); self->codestr_ptr = self->codestr; self->lineno = 1; self->par = 0; self->instr = 0; self->depth = 0; self->skip = 0; self->init = self->codestr; self->lose = self->codestr; self->start = NULL; self->end = NULL; #ifdef DEBUG fprintf(stderr, "\tScss BlockLocator object created (%ld units)!\n", self->codestr_sz); #endif } return self; }
PYTHON_METHOD_DEFINITION(ptImage, saveAsPNG, args) { PyObject* filenameObj; if (!PyArg_ParseTuple(args, "O", &filenameObj)) { PyErr_SetString(PyExc_TypeError, "saveAsPNG expects a string"); PYTHON_RETURN_ERROR; } if (PyUnicode_Check(filenameObj)) { int strLen = PyUnicode_GetSize(filenameObj); wchar_t* text = new wchar_t[strLen + 1]; PyUnicode_AsWideChar((PyUnicodeObject*)filenameObj, text, strLen); text[strLen] = L'\0'; self->fThis->SaveAsPNG(text); delete [] text; PYTHON_RETURN_NONE; } else if (PyString_Check(filenameObj)) { // we'll allow this, just in case something goes weird char* text = PyString_AsString(filenameObj); wchar_t* wText = hsStringToWString(text); self->fThis->SaveAsPNG(wText); delete [] wText; PYTHON_RETURN_NONE; } else { PyErr_SetString(PyExc_TypeError, "saveAsPNG expects a string"); PYTHON_RETURN_ERROR; } }
PYTHON_METHOD_DEFINITION(ptGUIControlListBox, addBranchW, args) { PyObject* textObj; char initiallyOpen; if (!PyArg_ParseTuple(args, "Ob", &textObj, &initiallyOpen)) { PyErr_SetString(PyExc_TypeError, "addBranchW expects a unicode string and a boolean"); PYTHON_RETURN_ERROR; } if (PyUnicode_Check(textObj)) { int strLen = PyUnicode_GetSize(textObj); wchar_t* name = new wchar_t[strLen + 1]; PyUnicode_AsWideChar((PyUnicodeObject*)textObj, name, strLen); name[strLen] = L'\0'; self->fThis->AddBranch(ST::string::from_wchar(name), initiallyOpen != 0); delete [] name; PYTHON_RETURN_NONE; } else if (PyString_Check(textObj)) { // we'll allow this, just in case something goes weird char* name = PyString_AsString(textObj); self->fThis->AddBranch(name, initiallyOpen != 0); PYTHON_RETURN_NONE; } else { PyErr_SetString(PyExc_TypeError, "addBranchW expects a unicode string and a boolean"); PYTHON_RETURN_ERROR; } }
PYTHON_METHOD_DEFINITION(ptVaultImageNode, setTitleW, args) { PyObject* textObj; if (!PyArg_ParseTuple(args, "O", &textObj)) { PyErr_SetString(PyExc_TypeError, "setTitleW expects a unicode string"); PYTHON_RETURN_ERROR; } if (PyUnicode_Check(textObj)) { int strLen = PyUnicode_GetSize(textObj); wchar_t* title = new wchar_t[strLen + 1]; PyUnicode_AsWideChar((PyUnicodeObject*)textObj, title, strLen); title[strLen] = L'\0'; self->fThis->Image_SetTitleW(title); delete [] title; PYTHON_RETURN_NONE; } else if (PyString_Check(textObj)) { // we'll allow this, just in case something goes weird char* title = PyString_AsString(textObj); self->fThis->Image_SetTitle(title); PYTHON_RETURN_NONE; } PyErr_SetString(PyExc_TypeError, "setTitleW expects a unicode string"); PYTHON_RETURN_ERROR; }
static PyObject * Reader_iternext(ReaderObj *self) { PyObject *lineobj; PyObject *fields = NULL; Py_UNICODE *line, c; Py_ssize_t linelen; if (parse_reset(self) < 0) return NULL; do { lineobj = PyIter_Next(self->input_iter); if (lineobj == NULL) { /* End of input OR exception */ if (!PyErr_Occurred() && self->field_len != 0) PyErr_Format(error_obj, "newline inside string"); return NULL; } if (!PyUnicode_Check(lineobj)) { PyErr_Format(error_obj, "iterator should return strings, " "not %.200s " "(did you open the file in text mode?)", lineobj->ob_type->tp_name ); Py_DECREF(lineobj); return NULL; } ++self->line_num; line = PyUnicode_AsUnicode(lineobj); linelen = PyUnicode_GetSize(lineobj); if (line == NULL || linelen < 0) { Py_DECREF(lineobj); return NULL; } while (linelen--) { c = *line++; if (c == '\0') { Py_DECREF(lineobj); PyErr_Format(error_obj, "line contains NULL byte"); goto err; } if (parse_process_char(self, c) < 0) { Py_DECREF(lineobj); goto err; } } Py_DECREF(lineobj); if (parse_process_char(self, 0) < 0) goto err; } while (self->state != START_RECORD); fields = self->fields; self->fields = NULL; err: return fields; }
TBool IsPythonString(PyObject* aString) { if (PyString_Check(aString)) { return PyString_Size(aString)>0; } else if (PyUnicode_Check(aString)) { return PyUnicode_GetSize(aString)>0; } PyErr_Clear(); return EFalse; }
bool py_to_qstr(PyObject *o, QString &str) { PyObject *u=NULL; if (!PyUnicode_Check(o)) { u=PyUnicode_FromObject(o); if (!u) return false; o=u; } #ifdef Py_UNICODE_WIDE str=QString::fromUcs4(PyUnicode_AsUnicode(o), PyUnicode_GetSize(o)); #else str.setUtf16(PyUnicode_AsUnicode(o), PyUnicode_GetSize(o)); #endif Py_XDECREF(u); return true; }
// Collator.find {{{ static PyObject * icu_Collator_find(icu_Collator *self, PyObject *args, PyObject *kwargs) { PyObject *a_, *b_; int32_t asz, bsz; UChar *a, *b; wchar_t *aw, *bw; UErrorCode status = U_ZERO_ERROR; UStringSearch *search = NULL; int32_t pos = -1, length = -1; if (!PyArg_ParseTuple(args, "UU", &a_, &b_)) return NULL; asz = (int32_t)PyUnicode_GetSize(a_); bsz = (int32_t)PyUnicode_GetSize(b_); a = (UChar*)calloc(asz*4 + 2, sizeof(UChar)); b = (UChar*)calloc(bsz*4 + 2, sizeof(UChar)); aw = (wchar_t*)calloc(asz*4 + 2, sizeof(wchar_t)); bw = (wchar_t*)calloc(bsz*4 + 2, sizeof(wchar_t)); if (a == NULL || b == NULL || aw == NULL || bw == NULL) return PyErr_NoMemory(); PyUnicode_AsWideChar((PyUnicodeObject*)a_, aw, asz*4+1); PyUnicode_AsWideChar((PyUnicodeObject*)b_, bw, bsz*4+1); u_strFromWCS(a, asz*4 + 1, NULL, aw, -1, &status); u_strFromWCS(b, bsz*4 + 1, NULL, bw, -1, &status); if (U_SUCCESS(status)) { search = usearch_openFromCollator(a, -1, b, -1, self->collator, NULL, &status); if (U_SUCCESS(status)) { pos = usearch_first(search, &status); if (pos != USEARCH_DONE) length = usearch_getMatchedLength(search); else pos = -1; } if (search != NULL) usearch_close(search); } free(a); free(b); free(aw); free(bw); return Py_BuildValue("ii", pos, length); } // }}}
static PyObject * filters_uwebsafe(PyObject * self, PyObject *args) { PyObject * com; Py_UNICODE * input_buffer; Py_UNICODE *buffer; PyObject * res; int ic=0, ib=0; int len; Py_UNICODE c; if (!(com = unicode_arg(args))) return NULL; input_buffer = PyUnicode_AS_UNICODE(com); len = PyUnicode_GetSize(com); buffer = (Py_UNICODE*)malloc(6*len*sizeof(Py_UNICODE)); for(ic = 0, ib = 0; ic < len; ic++, ib++) { c = input_buffer[ic]; if (c == '&') { buffer[ib++] = (Py_UNICODE)'&'; buffer[ib++] = (Py_UNICODE)'a'; buffer[ib++] = (Py_UNICODE)'m'; buffer[ib++] = (Py_UNICODE)'p'; buffer[ib] = (Py_UNICODE)';'; } else if(c == (Py_UNICODE)'<') { buffer[ib++] = (Py_UNICODE)'&'; buffer[ib++] = (Py_UNICODE)'l'; buffer[ib++] = (Py_UNICODE)'t'; buffer[ib] = (Py_UNICODE)';'; } else if(c == (Py_UNICODE)'>') { buffer[ib++] = (Py_UNICODE)'&'; buffer[ib++] = (Py_UNICODE)'g'; buffer[ib++] = (Py_UNICODE)'t'; buffer[ib] = (Py_UNICODE)';'; } else if(c == (Py_UNICODE)'"') { buffer[ib++] = (Py_UNICODE)'&'; buffer[ib++] = (Py_UNICODE)'q'; buffer[ib++] = (Py_UNICODE)'u'; buffer[ib++] = (Py_UNICODE)'o'; buffer[ib++] = (Py_UNICODE)'t'; buffer[ib] = (Py_UNICODE)';'; } else { buffer[ib] = input_buffer[ic]; } } res = PyUnicode_FromUnicode(buffer, ib); free(buffer); return res; }
static PyObject * astrcmp(PyObject *self, PyObject *args) { PyObject *s1, *s2; float d; const Py_UNICODE *us1, *us2; int len1, len2; PyThreadState *_save; if (!PyArg_ParseTuple(args, "UU", &s1, &s2)) return NULL; us1 = PyUnicode_AS_UNICODE(s1); us2 = PyUnicode_AS_UNICODE(s2); len1 = PyUnicode_GetSize(s1); len2 = PyUnicode_GetSize(s2); Py_UNBLOCK_THREADS d = LevenshteinDistance(us1, len1, us2, len2); Py_BLOCK_THREADS return Py_BuildValue("f", d); }
void CLocaLogicImpl::ConvertFromPythonString(TDes& aBuf, PyObject* aString) { aBuf.Zero(); if (PyString_Check(aString)) { TInt state=CCnvCharacterSetConverter::KStateDefault; TInt len=PyString_Size(aString); if (len > aBuf.MaxLength()) len=aBuf.MaxLength(); iCC->ConvertToUnicode(aBuf, TPtrC8((TUint8*)PyString_AsString(aString), len), state); } else if (PyUnicode_Check(aString)) { TInt len=PyUnicode_GetSize(aString)/2; if (len > aBuf.MaxLength()) len=aBuf.MaxLength(); aBuf=TPtrC((TUint16*)PyUnicode_AsUnicode(aString), len); } }
std::wstring Py2WString(PyObject* pyValue) { auto len = PyUnicode_GetSize(pyValue) + 1; wchar_t* w = new wchar_t[len]; if (PyUnicode_AsWideChar((PYUNICODEASVARCHARARG1TYPE*)pyValue, w, len) < 0) { delete[] w; throw MI::Exception(L"PyUnicode_AsWideChar failed"); } auto& value = std::wstring(w, len); delete[] w; return value; }
// Collator.startswith {{{ static PyObject * icu_Collator_startswith(icu_Collator *self, PyObject *args, PyObject *kwargs) { PyObject *a_, *b_; int32_t asz, bsz; int32_t actual_a, actual_b; UChar *a, *b; wchar_t *aw, *bw; UErrorCode status = U_ZERO_ERROR; int ans = 0; if (!PyArg_ParseTuple(args, "UU", &a_, &b_)) return NULL; asz = (int32_t)PyUnicode_GetSize(a_); bsz = (int32_t)PyUnicode_GetSize(b_); if (asz < bsz) Py_RETURN_FALSE; if (bsz == 0) Py_RETURN_TRUE; a = (UChar*)calloc(asz*4 + 2, sizeof(UChar)); b = (UChar*)calloc(bsz*4 + 2, sizeof(UChar)); aw = (wchar_t*)calloc(asz*4 + 2, sizeof(wchar_t)); bw = (wchar_t*)calloc(bsz*4 + 2, sizeof(wchar_t)); if (a == NULL || b == NULL || aw == NULL || bw == NULL) return PyErr_NoMemory(); actual_a = (int32_t)PyUnicode_AsWideChar((PyUnicodeObject*)a_, aw, asz*4+1); actual_b = (int32_t)PyUnicode_AsWideChar((PyUnicodeObject*)b_, bw, bsz*4+1); if (actual_a > -1 && actual_b > -1) { u_strFromWCS(a, asz*4 + 1, &actual_a, aw, -1, &status); u_strFromWCS(b, bsz*4 + 1, &actual_b, bw, -1, &status); if (U_SUCCESS(status) && ucol_equal(self->collator, a, actual_b, b, actual_b)) ans = 1; } free(a); free(b); free(aw); free(bw); if (ans) Py_RETURN_TRUE; Py_RETURN_FALSE; } // }}}
static PyObject *checkSynword(Splitter *self, PyObject *word) { /* Always returns a borrowed reference */ PyObject *value; if (PyUnicode_GetSize(word)==1 && ! self->allow_single_chars) { Py_INCREF(Py_None); return Py_None; } if (self->synstop) { value = PyDict_GetItem(self->synstop,word); if (value != NULL) { return value; } } return word; }
void CLocaLogicImpl::ConvertFromPythonString(auto_ptr<HBufC8>& aBuf, PyObject* aString) { if (PyString_Check(aString)) { TInt len=PyString_Size(aString); if (! aBuf.get() || aBuf->Des().MaxLength() < len) { aBuf.reset(HBufC8::NewL(len*2)); } aBuf->Des()=TPtrC8((TUint8*)PyString_AsString(aString), len); } else if (PyUnicode_Check(aString)) { TInt len=PyUnicode_GetSize(aString); if (! aBuf.get() || aBuf->Des().MaxLength() < len) { aBuf.reset(HBufC8::NewL(len*2)); } TPtr8 p=aBuf->Des(); iCC->ConvertFromUnicode(p, TPtrC((TUint16*)PyUnicode_AsUnicode(aString), len)); } PyErr_Clear(); }
void GetIndexOrName(PyObject *item, std::wstring& name, Py_ssize_t& i) { name.clear(); i = -1; #ifndef IS_PY3K if (PyString_Check(item)) { char* s = PyString_AsString(item); DWORD len = lstrlenA(s) + 1; wchar_t* w = new wchar_t[len]; if (::MultiByteToWideChar(CP_ACP, 0, s, len, w, len) != len) { delete [] w; throw MI::Exception(L"MultiByteToWideChar failed"); } name.assign(w, len); delete[] w; } else #endif if (PyUnicode_Check(item)) { Py_ssize_t len = PyUnicode_GetSize(item) + 1; wchar_t* w = new wchar_t[len]; if (PyUnicode_AsWideChar((PYUNICODEASVARCHARARG1TYPE*)item, w, len) < 0) { delete[] w; throw MI::Exception(L"PyUnicode_AsWideChar failed"); } name.assign(w, len); delete[] w; } else if (PyIndex_Check(item)) { i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) throw MI::Exception(L"Index error"); } else throw MI::Exception(L"Invalid name or index"); }
static int join_append_lineterminator(WriterObj *self) { int terminator_len; Py_UNICODE *terminator; terminator_len = PyUnicode_GetSize(self->dialect->lineterminator); if (terminator_len == -1) return 0; /* grow record buffer if necessary */ if (!join_check_rec_size(self, self->rec_len + terminator_len)) return 0; terminator = PyUnicode_AsUnicode(self->dialect->lineterminator); if (terminator == NULL) return 0; memmove(self->rec + self->rec_len, terminator, sizeof(Py_UNICODE)*terminator_len); self->rec_len += terminator_len; return 1; }
static int _set_char(const char *name, Py_UNICODE *target, PyObject *src, Py_UNICODE dflt) { if (src == NULL) *target = dflt; else { *target = '\0'; if (src != Py_None) { Py_UNICODE *buf; Py_ssize_t len; buf = PyUnicode_AsUnicode(src); len = PyUnicode_GetSize(src); if (buf == NULL || len > 1) { PyErr_Format(PyExc_TypeError, "\"%s\" must be an 1-character string", name); return -1; } if (len > 0) *target = buf[0]; } } return 0; }
void python_to_mathematica_object(PyObject *obj) { if(PyBool_Check(obj)) { if(obj==Py_True) MLPutSymbol(stdlink, "True"); else MLPutSymbol(stdlink, "False"); return; } if(PyInt_Check(obj)) { MLPutLongInteger(stdlink, PyInt_AsLong(obj)); return; } if(PyLong_Check(obj)) { #ifdef PYTHON25 Py_ssize_t length; #else int length; #endif char *str, *mat_expr; PyObject *long_as_str; long_as_str = PyObject_CallMethod(obj, "__str__", NULL); PyString_AsStringAndSize(long_as_str, &str, &length); MLPutFunction(stdlink, "ToExpression", 1); MLPutString(stdlink, str); Py_DECREF(long_as_str); return; } if(obj==Py_None) { MLPutSymbol(stdlink, "Null"); return; } if(PyFloat_Check(obj)) { MLPutDouble(stdlink, (double)PyFloat_AsDouble(obj)); return; } if(PyComplex_Check(obj)) { MLPutFunction(stdlink, "Complex", 2); MLPutDouble(stdlink, (double)PyComplex_RealAsDouble(obj)); MLPutDouble(stdlink, (double)PyComplex_ImagAsDouble(obj)); return; } if(PyString_Check(obj)) { char *str; #ifdef PYTHON25 Py_ssize_t length; #else int length; #endif PyString_AsStringAndSize(obj, &str, &length); MLPutByteString(stdlink, (unsigned char *)str, length); return; } if(PyUnicode_Check(obj)) { MLPutUnicodeString(stdlink, PyUnicode_AsUnicode(obj), PyUnicode_GetSize(obj) ); return; } if(PyTuple_Check(obj)) { mat_process_iterable_object(obj, "Can't get iterator for 'tuple'"); return; } if(PyList_Check(obj)) { mat_process_iterable_object(obj, "Can't get iterator for 'list'"); return; } #ifndef PYTHON23 if(PyObject_TypeCheck(obj, &PySet_Type)) { mat_process_iterable_object(obj, "Can't get iterator for 'set'"); return; } #endif if(PyDict_Check(obj)) { PyObject *items; items = PyDict_Items(obj); python_to_mathematica_object(items); Py_DECREF(items); return; } // This should ideally print info, like type of the object, that // can't be converted. MLPutString(stdlink, "Object type can't be converted!"); }
static PyObject * filters_uspace_compress(PyObject * self, PyObject *args) { PyObject * com; PyObject * res; Py_ssize_t len; Py_UNICODE *input_buffer; Py_UNICODE *buffer; Py_UNICODE c; int ic, ib; int gobble = 1; com = unicode_arg(args); if(!com) { return NULL; } input_buffer = PyUnicode_AS_UNICODE(com); len = PyUnicode_GetSize(com); buffer = (Py_UNICODE*)malloc(len * sizeof(Py_UNICODE)); /* ic -> input buffer index, ib -> output buffer */ for(ic = 0, ib = 0; ic <= len; ic++) { c = input_buffer[ic]; /* gobble -> we are space compressing */ if(gobble) { /* remove spaces if encountered */ if(Py_UNICODE_ISSPACE(c)) { /* after this loop, c will be a non-space */ while(Py_UNICODE_ISSPACE(c)) { c = input_buffer[++ic]; } /* unless next char is a <, add a single space to account for the multiple spaces that have been removed */ if(c != (Py_UNICODE)('<')) { buffer[ib++] = (Py_UNICODE)(' '); } } /* gobble all space after '>' */ if(c == (Py_UNICODE)('>')) { buffer[ib++] = c; c = input_buffer[++ic]; while(Py_UNICODE_ISSPACE(c)) { c = input_buffer[++ic]; } } /* does the next part of the string match the SC_OFF label */ if (len - ic >= SC_OFF_LEN && memcmp(&input_buffer[ic], SC_OFF_U, sizeof(Py_UNICODE)*SC_OFF_LEN) == 0) { /* disable gobbling, and bypass that part of the string */ gobble = 0; ic += SC_OFF_LEN; c = input_buffer[ic]; } } /* not gobbling, but find the SC_ON tag */ else if (len - ic >= SC_ON_LEN && memcmp(&input_buffer[ic], SC_ON_U, sizeof(Py_UNICODE)*SC_ON_LEN) == 0) { gobble = 1; ic += SC_ON_LEN; c = input_buffer[ic]; } if(c) { buffer[ib++] = c; } } res = PyUnicode_FromUnicode(buffer, ib); free(buffer); return res; }
static int Context_setWorkgroup (Context *self, PyObject *value, void *closure) { wchar_t *w_workgroup; size_t chars; char *workgroup; size_t bytes; ssize_t written; #if PY_MAJOR_VERSION < 3 if (PyString_Check (value)) value = PyUnicode_FromString (PyString_AsString (value)); #endif if (!PyUnicode_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be string"); return -1; } chars = PyUnicode_GetSize (value); /* not including NUL */ w_workgroup = malloc ((chars + 1) * sizeof (wchar_t)); if (!w_workgroup) { PyErr_NoMemory (); return -1; } #if PY_MAJOR_VERSION < 3 if (PyUnicode_AsWideChar ((PyUnicodeObject *) value, w_workgroup, chars) == -1) #else if (PyUnicode_AsWideChar (value, w_workgroup, chars) == -1) #endif { free (w_workgroup); return -1; } w_workgroup[chars] = L'\0'; bytes = MB_CUR_MAX * chars + 1; /* extra byte for NUL */ workgroup = malloc (bytes); if (!workgroup) { free (w_workgroup); PyErr_NoMemory (); return -1; } written = wcstombs (workgroup, w_workgroup, bytes); free (w_workgroup); if (written == -1) workgroup[0] = '\0'; else /* NUL-terminate it (this is why we allocated the extra byte) */ workgroup[written] = '\0'; smbc_setWorkgroup (self->context, workgroup); // Don't free workgroup: the API function just takes a reference(!) return 0; }
static PyObject* translate_to_ucs2(PyObject* o) { PyObject* translated = NULL; Py_ssize_t len; wchar_t* unicode; assert(PyUnicode_Check(o)); #if PY_MAJOR_VERSION < 3 len = PyUnicode_GetSize(o); do { unicode = tds_mem_malloc((size_t)len * sizeof(wchar_t)); if (!unicode) { PyErr_NoMemory(); break; } if (-1 == PyUnicode_AsWideChar((PyUnicodeObject*)o, unicode, len)) { break; } } while (0); #else /* if PY_MAJOR_VERSION < 3 */ unicode = PyUnicode_AsWideCharString(o, &len); #endif /* else if PY_MAJOR_VERSION < 3 */ if (!PyErr_Occurred()) { Py_ssize_t ixsrc, ixdst = 0; for (ixsrc = 0; ixsrc < len; ++ixsrc, ++ixdst) { #if defined(WCHAR_T_UCS4) if (0xFFFF < unicode[ixsrc]) #else /* if defined(WCHAR_T_UCS4) */ if (Py_UNICODE_IS_SURROGATE(unicode[ixsrc])) #endif /* else if defined(WCHAR_T_UCS4) */ { static const char s_fmt[] = "Unicode codepoint U+%08X is not representable in UCS-2; replaced with U+FFFD"; char buffer[ARRAYSIZE(s_fmt) + 8 /* for codepoint chars */]; #if defined(WCHAR_T_UCS4) uint32_t codepoint = (uint32_t)unicode[ixsrc]; #else /* if defined(WCHAR_T_UCS4) */ uint32_t codepoint; assert(((ixsrc + 1) < len) && Py_UNICODE_IS_SURROGATE(unicode[ixsrc + 1])); codepoint = Py_UNICODE_JOIN_SURROGATES(unicode[ixsrc], unicode[ixsrc + 1]); ++ixsrc; #endif /* else if defined(WCHAR_T_UCS4) */ (void)sprintf(buffer, s_fmt, codepoint); if (0 != PyErr_WarnEx(PyExc_UnicodeWarning, buffer, 1)) { break; } unicode[ixdst] = 0xFFFD; /* unicode replacement character */ } #if !defined(WCHAR_T_UCS4) else { unicode[ixdst] = unicode[ixsrc]; } #endif /* if !defined(WCHAR_T_UCS4) */ } if (!PyErr_Occurred()) { translated = PyUnicode_FromWideChar(unicode, ixdst); } } #if PY_MAJOR_VERSION < 3 tds_mem_free(unicode); #else /* if PY_MAJOR_VERSION < 3 */ PyMem_Free(unicode); #endif /* else if PY_MAJOR_VERSION < 3 */ return translated; }
/** Convert a PyObject to a TValue as used when calling functions and setting properties in a generic way through Delphi RTTI. * \param O: PyObject to convert * \param TypeInfo: The expected return type * \return A TValue with a value of the type given by TypeInfo. * \throw EPyVclError on conversion errors. */ TValue ToValue(PyObject *O, TTypeInfo *TypeInfo) { TValue Result; switch(TypeInfo->Kind) { case tkClass: if(VclObject_Check(O)) Result = TValue::From(VclObject_AsObject(O)); else if(O == Py_None || PyLong_Check(O)) Result = TValue::From((TObject*)(O == Py_None ? NULL : PyLong_AsLong(O))); else throw EPyVclError("Cannot convert Python object of type '" + String(O->ob_type->tp_name) + "' to '" + AnsiString(TypeInfo->Name) + "'"); break; case tkEnumeration: if(PyUnicode_Check(O)) TValue::Make(GetEnumValue(TypeInfo, PyUnicode_AsUnicode(O)), TypeInfo, Result); if(PyLong_Check(O)) TValue::Make(PyLong_AsLong(O), TypeInfo, Result); break; case tkSet: TValue::Make(StringToSet(TypeInfo, PyUnicode_AsUnicode(O)), TypeInfo, Result); break; case tkInteger: Result = TValue::From(PyLong_AsUnsignedLongMask(O)); break; case tkUString: case tkString: case tkLString: case tkWString: Result = TValue::From(String(PyUnicode_AsUnicode(O))); break; case tkChar: case tkWChar: if(PyUnicode_GetSize(O) != 1) throw EPyVclError("Expected string with one character"); Result = TValue::From(PyUnicode_AsUnicode(O)[0]); break; case tkFloat: Result = TValue::From(PyFloat_AsDouble(O)); break; case tkRecord: { TRttiType *Type = Context.GetType(TypeInfo); std::vector<BYTE> Data(Type->TypeSize); DynamicArray<TRttiField*> Fields = Type->GetFields(); if(PyTuple_Size(O) != Fields.Length) throw EPyVclError("Expected tuple with " + IntToStr(Fields.Length) + " elements"); for(int I = 0; I < Fields.Length; I++) Fields[I]->SetValue(&Data[0], ToValue(PyTuple_GetItem(O, I), Fields[I]->FieldType->Handle)); TValue::Make(&Data[0], TypeInfo, Result); break; } case tkInt64: Result = TValue::From(PyLong_AsLongLong(O)); break; case tkPointer: if(AnsiString(TypeInfo->Name) == "PWideChar") TValue::Make(reinterpret_cast<int>(PyUnicode_AsUnicode(O)), TypeInfo, Result); else throw EPyVclError("Cannot convert Python object of type '" + String(O->ob_type->tp_name) + "' to '" + AnsiString(TypeInfo->Name) + "'"); break; case tkVariant: case tkArray: case tkInterface: case tkDynArray: case tkClassRef: case tkProcedure: case tkUnknown: case tkMethod: default: throw EPyVclError("Cannot convert Python object of type '" + String(O->ob_type->tp_name) + "' to '" + AnsiString(TypeInfo->Name) + "'"); } if(PyErr_Occurred()) throw EPyVclError("Cannot convert Python object of type '" + String(O->ob_type->tp_name) + "' to '" + AnsiString(TypeInfo->Name) + "'"); return Result; }
static gboolean marshal_value(CORBA_TypeCode tc, gconstpointer *val, PyObject *value) { gboolean ret = FALSE; gint i; while (tc->kind == CORBA_tk_alias) tc = tc->subtypes[0]; switch (tc->kind) { case CORBA_tk_null: case CORBA_tk_void: ret = (value == Py_None); break; case CORBA_tk_short: alignval(val, ORBIT_ALIGNOF_CORBA_SHORT); getval(val, CORBA_short) = PyInt_AsLong(value); advanceptr(val, sizeof(CORBA_short)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_long: alignval(val, ORBIT_ALIGNOF_CORBA_LONG); getval(val, CORBA_long) = PyInt_AsLong(value); advanceptr(val, sizeof(CORBA_long)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_ushort: alignval(val, ORBIT_ALIGNOF_CORBA_SHORT); getval(val, CORBA_unsigned_short) = PyInt_AsLong(value); advanceptr(val, sizeof(CORBA_unsigned_short)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_ulong: case CORBA_tk_enum: alignval(val, ORBIT_ALIGNOF_CORBA_LONG); if (PyLong_Check(value)) getval(val, CORBA_unsigned_long) = PyLong_AsUnsignedLong(value); else getval(val, CORBA_unsigned_long) = PyInt_AsLong(value); advanceptr(val, sizeof(CORBA_unsigned_long)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_float: alignval(val, ORBIT_ALIGNOF_CORBA_FLOAT); getval(val, CORBA_float) = PyFloat_AsDouble(value); advanceptr(val, sizeof(CORBA_float)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_double: alignval(val, ORBIT_ALIGNOF_CORBA_DOUBLE); getval(val, CORBA_double) = PyFloat_AsDouble(value); advanceptr(val, sizeof(CORBA_double)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_boolean: getval(val, CORBA_boolean) = PyObject_IsTrue(value); advanceptr(val, sizeof(CORBA_boolean)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_char: if (PyString_Check(value) && PyString_Size(value) == 1) { getval(val, CORBA_char) = PyString_AsString(value)[0]; advanceptr(val, sizeof(CORBA_char)); ret = TRUE; } break; case CORBA_tk_octet: getval(val, CORBA_long) = PyInt_AsLong(value); advanceptr(val, sizeof(CORBA_octet)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_any: if (PyObject_TypeCheck(value, &PyCORBA_Any_Type)) { alignval(val, ORBIT_ALIGNOF_CORBA_ANY); CORBA_any__copy(&getval(val, CORBA_any), &((PyCORBA_Any *)value)->any); advanceptr(val, sizeof(CORBA_any)); ret = TRUE; } break; case CORBA_tk_TypeCode: alignval(val, ORBIT_ALIGNOF_CORBA_POINTER); if (PyObject_TypeCheck(value, &PyCORBA_TypeCode_Type)) { getval(val, CORBA_TypeCode) = (CORBA_TypeCode)CORBA_Object_duplicate( (CORBA_Object)((PyCORBA_TypeCode *)value)->tc, NULL); ret = TRUE; } advanceptr(val, sizeof(CORBA_TypeCode)); break; case CORBA_tk_Principal: g_warning("can't marshal Principal"); break; case CORBA_tk_objref: alignval(val, ORBIT_ALIGNOF_CORBA_POINTER); if (value == Py_None) { getval(val, CORBA_Object) = CORBA_OBJECT_NIL; ret = TRUE; } else if (PyObject_TypeCheck(value, &PyCORBA_Object_Type)) { CORBA_Object objref = ((PyCORBA_Object *)value)->objref; getval(val, CORBA_Object) = CORBA_Object_duplicate(objref, NULL); advanceptr(val, sizeof(CORBA_Object)); ret = TRUE; } break; case CORBA_tk_except: case CORBA_tk_struct: alignval(val, tc->c_align); for (i = 0; i < tc->sub_parts; i++) { gchar *pyname; PyObject *item; gboolean itemret; pyname = _pyorbit_escape_name(tc->subnames[i]); item = PyObject_GetAttrString(value, pyname); g_free(pyname); if (!item) break; itemret = marshal_value(tc->subtypes[i], val, item); Py_DECREF(item); if (!itemret) break; } if (i == tc->sub_parts) ret = TRUE; /* no error */ break; case CORBA_tk_union: { PyObject *discrim, *subval; CORBA_TypeCode subtc; gconstpointer body; int sz = 0; discrim = PyObject_GetAttrString(value, "_d"); if (!discrim) break; subval = PyObject_GetAttrString(value, "_v"); if (!subval) break; alignval(val, MAX(tc->c_align, tc->discriminator->c_align)); ret = marshal_value(tc->discriminator, val, discrim); if (!ret) { Py_DECREF(discrim); Py_DECREF(subval); break; } /* calculate allocation info */ for (i = 0; i < tc->sub_parts; i++) { sz = MAX(sz, ORBit_gather_alloc_info(tc->subtypes[i])); } subtc = get_union_tc(tc, discrim); Py_DECREF(discrim); if (!subtc) { Py_DECREF(subval); break; } alignval(val, tc->c_align); body = *val; ret = marshal_value(subtc, &body, subval); Py_DECREF(subval); advanceptr(val, sz); break; } case CORBA_tk_string: if (PyString_Check(value)) { /* error out if python string is longer than the bound * specified in the string typecode. */ if (tc->length > 0 && PyString_Size(value) > tc->length) break; alignval(val, ORBIT_ALIGNOF_CORBA_POINTER); getval(val, CORBA_string) = CORBA_string_dup(PyString_AsString(value)); advanceptr(val, sizeof(CORBA_char *)); ret = TRUE; } break; case CORBA_tk_sequence: if (PySequence_Check(value)) { CORBA_sequence_CORBA_octet *sval; gconstpointer seqval; gint i; /* error out if python sequence is longer than the bound * specified in the sequence typecode. */ if (tc->length > 0 && PySequence_Length(value) > tc->length) break; alignval(val, ORBIT_ALIGNOF_CORBA_SEQ); sval = (CORBA_sequence_CORBA_octet *)*val; if (CORBA_TypeCode_equal(tc->subtypes[0], TC_CORBA_octet, NULL) && PyString_Check(value)) { Py_ssize_t length; char *buffer; if (PyString_AsStringAndSize(value, &buffer, &length) == -1) ret = FALSE; else { sval->_release = CORBA_TRUE; sval->_buffer = ORBit_alloc_tcval(TC_CORBA_octet, length); memcpy(sval->_buffer, buffer, length); sval->_length = length; ret = TRUE; } } else { sval->_release = TRUE; sval->_length = PySequence_Length(value); sval->_buffer = ORBit_alloc_tcval(tc->subtypes[0], sval->_length); seqval = sval->_buffer; for (i = 0; i < sval->_length; i++) { PyObject *item = PySequence_GetItem(value, i); gboolean itemret; if (!item) break; itemret = marshal_value(tc->subtypes[0], &seqval, item); Py_DECREF(item); if (!itemret) break; } if (i == sval->_length) ret = TRUE; /* no error */ } advanceptr(val, sizeof(CORBA_sequence_CORBA_octet)); } break; case CORBA_tk_array: if (PySequence_Check(value) && PySequence_Length(value) == tc->length) { gint i; for (i = 0; i < tc->length; i++) { PyObject *item = PySequence_GetItem(value, i); gboolean itemret; if (!item) break; itemret = marshal_value(tc->subtypes[0], val, item); Py_DECREF(item); if (!itemret) break; } if (i == tc->length) ret = TRUE; /* no error */ } break; case CORBA_tk_longlong: alignval(val, ORBIT_ALIGNOF_CORBA_LONG_LONG); if (PyLong_Check(value)) getval(val, CORBA_long_long) = PyLong_AsLongLong(value); else getval(val, CORBA_long_long) = PyInt_AsLong(value); advanceptr(val, sizeof(CORBA_long_long)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_ulonglong: alignval(val, ORBIT_ALIGNOF_CORBA_LONG_LONG); if (PyLong_Check(value)) getval(val, CORBA_unsigned_long_long) =PyLong_AsUnsignedLongLong(value); else getval(val, CORBA_unsigned_long_long) = PyInt_AsLong(value); advanceptr(val, sizeof(CORBA_unsigned_long_long)); if (!PyErr_Occurred()) ret = TRUE; break; case CORBA_tk_longdouble: g_warning("can't marshal long double"); break; case CORBA_tk_wchar: if (PyUnicode_Check(value) && PyUnicode_GetSize(value) == 1) { alignval(val, ORBIT_ALIGNOF_CORBA_SHORT); getval(val, CORBA_wchar) = PyUnicode_AsUnicode(value)[0]; advanceptr(val, sizeof(CORBA_wchar)); ret = TRUE; } break; case CORBA_tk_wstring: if (PyUnicode_Check(value)) { int length = PyUnicode_GetSize(value); Py_UNICODE *unicode = PyUnicode_AsUnicode(value); CORBA_wchar *wstr; /* error out if python unicode string is longer than the * bound specified in the wstring typecode. */ if (tc->length > 0 && length > tc->length) break; alignval(val, ORBIT_ALIGNOF_CORBA_POINTER); wstr = CORBA_wstring_alloc(length); getval(val, CORBA_wstring) = wstr; for (i = 0; i < length; i++) { wstr[i] = unicode[i]; } advanceptr(val, sizeof(CORBA_wchar *)); ret = TRUE; } break; default: g_warning("unhandled typecode: %s (kind=%d)", tc->repo_id, tc->kind); break; } if (!ret) PyErr_Clear(); return ret; }
/* * Returns a copy of the given string (8-bit or Unicode) with the XML * control characters converted to XML character entities. * * If an 8-bit string is passed in, an 8-bit string is returned. If a * Unicode string is passed in, a Unicode string is returned. */ static PyObject* _escape_xml(PyObject* self, PyObject *args, const char** escapes) { PyObject* input_obj; PyObject* input_coerce = NULL; PyObject* output_obj; int count = 0; Py_UNICODE* uinput = NULL; char* input = NULL; Py_ssize_t input_len; Py_UNICODE* uoutput = NULL; char* output = NULL; Py_UNICODE* up = NULL; char* p = NULL; Py_ssize_t i; const char** esc; const char* ent; if (!PyArg_ParseTuple(args, "O:escape_xml", &input_obj)) { return NULL; } /* First, try as Unicode */ if (!PyBytes_Check(input_obj)) { input_coerce = PyObject_Str(input_obj); } if (input_coerce) { uinput = PyUnicode_AsUnicode(input_coerce); if (uinput == NULL) { Py_DECREF(input_coerce); return NULL; } input_len = PyUnicode_GetSize(input_coerce); for (i = 0; i < input_len; ++i) { for (esc = escapes; ; esc += 2) { if (uinput[i] > (Py_UNICODE)**esc) { break; } else if (uinput[i] == (Py_UNICODE)**esc) { ++count; break; } } } if (count) { uoutput = malloc((input_len + 1 + count * 5) * sizeof(Py_UNICODE)); if (uoutput == NULL) { Py_DECREF(input_coerce); PyErr_SetString(PyExc_MemoryError, "Out of memory"); return NULL; } up = uoutput; for (i = 0; i < input_len; ++i) { for (esc = escapes; ; esc += 2) { if (uinput[i] > (Py_UNICODE)**esc) { *(up++) = uinput[i]; break; } else if (uinput[i] == (Py_UNICODE)**esc) { for (ent = *(esc + 1); *ent != '\0'; ++ent) { *(up++) = (Py_UNICODE)*ent; } break; } } } *up = 0; Py_DECREF(input_coerce); output_obj = PyUnicode_FromUnicode(uoutput, up - uoutput); free(uoutput); return output_obj; } else { return input_coerce; } } /* Now try as bytes */ input_coerce = PyObject_Bytes(input_obj); if (input_coerce) { if (PyBytes_AsStringAndSize(input_coerce, &input, &input_len) == -1) { Py_DECREF(input_coerce); return NULL; } for (i = 0; i < input_len; ++i) { for (esc = escapes; ; esc += 2) { if (input[i] > **esc) { break; } else if (input[i] == **esc) { ++count; break; } } } if (count) { output = malloc((input_len + 1 + count * 5) * sizeof(char)); if (output == NULL) { Py_DECREF(input_coerce); PyErr_SetString(PyExc_MemoryError, "Out of memory"); return NULL; } p = output; for (i = 0; i < input_len; ++i) { for (esc = escapes; ; esc += 2) { if (input[i] > **esc) { *(p++) = input[i]; break; } else if (input[i] == **esc) { for (ent = *(esc + 1); *ent != '\0'; ++ent) { *(p++) = *ent; } break; } } } *p = 0; Py_DECREF(input_coerce); output_obj = PyBytes_FromStringAndSize(output, p - output); free(output); return output_obj; } else { return input_coerce; } } PyErr_SetString(PyExc_TypeError, "must be convertible to str or bytes"); return NULL; }