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; }
int _Py_stat(PyObject *path, struct stat *statbuf) { #ifdef MS_WINDOWS int err; struct _stat wstatbuf; wchar_t *wpath; wpath = PyUnicode_AsUnicode(path); if (wpath == NULL) return -2; err = _wstat(wpath, &wstatbuf); if (!err) statbuf->st_mode = wstatbuf.st_mode; return err; #else int ret; PyObject *bytes = PyUnicode_EncodeFSDefault(path); if (bytes == NULL) return -2; ret = stat(PyBytes_AS_STRING(bytes), statbuf); Py_DECREF(bytes); return ret; #endif }
FILE* _Py_fopen(PyObject *path, const char *mode) { #ifdef MS_WINDOWS wchar_t *wpath; wchar_t wmode[10]; int usize; if (!PyUnicode_Check(path)) { PyErr_Format(PyExc_TypeError, "str file path expected under Windows, got %R", Py_TYPE(path)); return NULL; } wpath = PyUnicode_AsUnicode(path); if (wpath == NULL) return NULL; usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode)); if (usize == 0) return NULL; return _wfopen(wpath, wmode); #else FILE *f; PyObject *bytes; if (!PyUnicode_FSConverter(path, &bytes)) return NULL; f = fopen(PyBytes_AS_STRING(bytes), mode); Py_DECREF(bytes); return f; #endif }
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; }
// String conversions // Convert a Python object to a WCHAR - allow embedded NULLs, None, etc. BOOL PyWinObject_AsWCHAR(PyObject *stringObject, WCHAR **pResult, BOOL bNoneOK /*= FALSE*/,DWORD *pResultLen /*= NULL*/) { BOOL rc = TRUE; int resultLen = 0; #if (PY_VERSION_HEX < 0x03000000) // Do NOT accept 'bytes' object when a plain 'WCHAR' is needed on py3k. if (PyString_Check(stringObject)) { int size=PyString_Size(stringObject); const char *buf = PyString_AsString(stringObject); if (buf==NULL) return FALSE; /* We assume that we dont need more 'wide characters' for the result then the number of bytes in the input. Often we will need less, as the input may contain multi-byte chars, but we should never need more */ *pResult = (LPWSTR)PyMem_Malloc((size+1)*sizeof(WCHAR)); if (*pResult==NULL) { PyErr_SetString(PyExc_MemoryError, "No memory for wide string buffer"); return FALSE; } /* convert and get the final character size */ resultLen = MultiByteToWideChar(CP_ACP, 0, buf, size, *pResult, size); /* terminate the string */ (*pResult)[resultLen] = L'\0'; } else #endif // py3k if (PyUnicode_Check(stringObject)) { resultLen = PyUnicode_GET_SIZE(stringObject); size_t cb = sizeof(WCHAR) * (resultLen+1); *pResult = (WCHAR *)PyMem_Malloc(cb); if (*pResult==NULL) { PyErr_SetString(PyExc_MemoryError, "Allocating WCHAR array"); return FALSE; } // copy the value, including embedded NULLs memcpy(*pResult, PyUnicode_AsUnicode(stringObject), cb); } else if (stringObject == Py_None) { if (bNoneOK) { *pResult = NULL; } else { PyErr_SetString(PyExc_TypeError, "None is not a valid string in this context"); rc = FALSE; } } else { const char *tp_name = stringObject && stringObject->ob_type ? stringObject->ob_type->tp_name : "<NULL!!>"; PyErr_Format(PyExc_TypeError, "Objects of type '%s' can not be converted to Unicode.", tp_name); rc = FALSE; } if (rc && pResultLen) *pResultLen = resultLen; return rc; }
static int add_to_data(ligolw_Tokenizer *tokenizer, PyObject *unicode) { Py_ssize_t n = PyUnicode_GET_SIZE(unicode); if(n) { if(tokenizer->length - tokenizer->data + n > tokenizer->allocation) { /* * convert pointers to integer offsets */ ptrdiff_t pos = tokenizer->pos - tokenizer->data; ptrdiff_t length = tokenizer->length - tokenizer->data; /* * increase buffer size, adding 1 to leave room for * the null terminator */ Py_UNICODE *old_data = tokenizer->data; tokenizer->data = realloc(tokenizer->data, (tokenizer->allocation + n + 1) * sizeof(*tokenizer->data)); if(!tokenizer->data) { /* * memory failure, restore pointer and exit */ tokenizer->data = old_data; return -1; } tokenizer->allocation += n; /* * convert integer offsets back to pointers */ tokenizer->pos = &tokenizer->data[pos]; tokenizer->length = &tokenizer->data[length]; } /* * copy data from unicode into buffer, appending null * terminator */ memcpy(tokenizer->length, PyUnicode_AsUnicode(unicode), n * sizeof(*tokenizer->length)); tokenizer->length += n; *tokenizer->length = 0; } /* * success */ return 0; }
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; }
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); } }
char * PyUnicode_AsPgString(PyObject *p_unicode) { Py_ssize_t unicode_size = PyUnicode_GET_SIZE(p_unicode); char *message = NULL; PyObject *pTempStr = PyUnicode_Encode(PyUnicode_AsUnicode(p_unicode), unicode_size, GetDatabaseEncodingName(), NULL); errorCheck(); message = strdup(PyBytes_AsString(pTempStr)); errorCheck(); Py_DECREF(pTempStr); return message; }
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(); }
static bool GetUnicodeInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info) { Py_UNICODE* pch = PyUnicode_AsUnicode(param); Py_ssize_t len = PyUnicode_GET_SIZE(param); info.ValueType = SQL_C_WCHAR; info.ColumnSize = (SQLUINTEGER)max(len, 1); if (len <= cur->cnxn->wvarchar_maxlength) { if (SQLWCHAR_SIZE == Py_UNICODE_SIZE) { info.ParameterValuePtr = pch; } else { // SQLWCHAR and Py_UNICODE are not the same size, so we need to allocate and copy a buffer. if (len > 0) { info.ParameterValuePtr = SQLWCHAR_FromUnicode(pch, len); if (info.ParameterValuePtr == 0) return false; info.allocated = true; } else { info.ParameterValuePtr = pch; } } info.ParameterType = SQL_WVARCHAR; info.StrLen_or_Ind = (SQLINTEGER)(len * sizeof(SQLWCHAR)); } else { // Too long to pass all at once, so we'll provide the data at execute. info.ParameterType = SQL_WLONGVARCHAR; info.StrLen_or_Ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLLEN)len * sizeof(SQLWCHAR)) : SQL_DATA_AT_EXEC; info.ParameterValuePtr = param; } return true; }
char * PyUnicode_AsPgString(PyObject *p_unicode) { Py_ssize_t unicode_size; char *message = NULL; PyObject *pTempStr; if (p_unicode == NULL) { elog(ERROR, "Received a null pointer in pyunicode_aspgstring"); } unicode_size = PyUnicode_GET_SIZE(p_unicode); pTempStr = PyUnicode_Encode(PyUnicode_AsUnicode(p_unicode), unicode_size, getPythonEncodingName(), NULL); errorCheck(); message = strdup(PyBytes_AsString(pTempStr)); errorCheck(); Py_DECREF(pTempStr); return message; }
/** Retrieve a type, function or global variable from the global vcl object. * The name is searched in this ordier: * 1. Check the cache if the object already exists and used it if it does. * Global variables as Application always exist here. * 2. Search for type in custom list of available types. * 3. Try to retrieve it as a registered class in Delphi. * 4. Try to create it as a global function. * At last the object is stored in the cache for fast retrievel next time. * A Python exception is thrown if no variable, type or function with the given name is found. * \return New reference */ static PyObject* GlobalVcl_GetAttro(PyObject *self, PyObject *attr_name) { try { PyObject *Result = PyObject_GenericGetAttr(self, attr_name); if(Result != NULL) return Result; PyErr_Clear(); String Name = PyUnicode_AsUnicode(attr_name); TRttiType *Type = Context.GetType(LookUpClass(Name)); if(Type == NULL) { TClass Class = GetClass(Name); if(Class) Type = Context.GetType(Class); } if(Type != NULL) { // if(Class->InheritsFrom(__classid(Exception))) Result = VclType_Create(Type); } else Result = VclFunction_Create(Name); if(Result == NULL) { SetErrorString(PyExc_AttributeError, "VCL has no global attribute '" + Name + "'"); return NULL; } PyObject_GenericSetAttr(self, attr_name, Result); return Result; } catch(...) { return PyVclHandleException(); } }
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; }
/* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":80 */ Py_INCREF(((PyObject *)__pyx_v_ret)); __pyx_r = ((PyObject *)__pyx_v_ret); goto __pyx_L0; goto __pyx_L2; } __pyx_L2:; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("_pymfclib_winhttp.getIEProxyConfigForCurrentUser"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_ret); return __pyx_r; } static int __pyx_f_17_pymfclib_winhttp_14WinHTTPSession___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_f_17_pymfclib_winhttp_14WinHTTPSession___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_agent = 0; HINTERNET __pyx_v_handle; int __pyx_r; __pyx_t_17_pymfclib_winhttp_PYMFC_WCHAR *__pyx_1; int __pyx_2; static char *__pyx_argnames[] = {"agent",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_agent)) return -1; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_agent); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":87 */ __pyx_1 = PyUnicode_AsUnicode(__pyx_v_agent); if (__pyx_1 == NULL) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} __pyx_v_handle = WinHttpOpen(__pyx_1,WINHTTP_ACCESS_TYPE_NO_PROXY,NULL,NULL,0); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":88 */ __pyx_2 = (!(__pyx_v_handle != 0)); if (__pyx_2) { pymRaiseWin32Err(); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":90 */ ((struct __pyx_obj_17_pymfclib_winhttp_WinHTTPSession *)__pyx_v_self)->hInternet = __pyx_v_handle; __pyx_r = 0; goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("_pymfclib_winhttp.WinHTTPSession.__init__"); __pyx_r = -1; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_agent); return __pyx_r; }
static char *GetPythonImport (HINSTANCE hModule) { unsigned char *dllbase, *import_data, *import_name; DWORD pe_offset, opt_offset; WORD opt_magic; int num_dict_off, import_off; /* Safety check input */ if (hModule == NULL) { return NULL; } /* Module instance is also the base load address. First portion of memory is the MS-DOS loader, which holds the offset to the PE header (from the load base) at 0x3C */ dllbase = (unsigned char *)hModule; pe_offset = DWORD_AT(dllbase + 0x3C); /* The PE signature must be "PE\0\0" */ if (memcmp(dllbase+pe_offset,"PE\0\0",4)) { return NULL; } /* Following the PE signature is the standard COFF header (20 bytes) and then the optional header. The optional header starts with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ uses 64-bits for some fields). It might also be 0x107 for a ROM image, but we don't process that here. The optional header ends with a data dictionary that directly points to certain types of data, among them the import entries (in the second table entry). Based on the header type, we determine offsets for the data dictionary count and the entry within the dictionary pointing to the imports. */ opt_offset = pe_offset + 4 + 20; opt_magic = WORD_AT(dllbase+opt_offset); if (opt_magic == 0x10B) { /* PE32 */ num_dict_off = 92; import_off = 104; } else if (opt_magic == 0x20B) { /* PE32+ */ num_dict_off = 108; import_off = 120; } else { /* Unsupported */ return NULL; } /* Now if an import table exists, offset to it and walk the list of imports. The import table is an array (ending when an entry has empty values) of structures (20 bytes each), which contains (at offset 12) a relative address (to the module base) at which a string constant holding the import name is located. */ if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { /* We have at least 2 tables - the import table is the second one. But still it may be that the table size is zero */ if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) return NULL; import_data = dllbase + DWORD_AT(dllbase + opt_offset + import_off); while (DWORD_AT(import_data)) { import_name = dllbase + DWORD_AT(import_data+12); if (strlen(import_name) >= 6 && !strncmp(import_name,"python",6)) { char *pch; #ifndef _DEBUG /* In a release version, don't claim that python3.dll is a Python DLL. */ if (strcmp(import_name, "python3.dll") == 0) { import_data += 20; continue; } #endif /* Ensure python prefix is followed only by numbers to the end of the basename */ pch = import_name + 6; #ifdef _DEBUG while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { #else while (*pch && *pch != '.') { #endif if (*pch >= '0' && *pch <= '9') { pch++; } else { pch = NULL; break; } } if (pch) { /* Found it - return the name */ return import_name; } } import_data += 20; } } return NULL; } dl_funcptr _PyImport_GetDynLoadWindows(const char *shortname, PyObject *pathname, FILE *fp) { dl_funcptr p; char funcname[258], *import_python; wchar_t *wpathname; #ifndef _DEBUG _Py_CheckPython3(); #endif wpathname = PyUnicode_AsUnicode(pathname); if (wpathname == NULL) return NULL; PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); { HINSTANCE hDLL = NULL; unsigned int old_mode; #if HAVE_SXS ULONG_PTR cookie = 0; #endif /* Don't display a message box when Python can't load a DLL */ old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); #if HAVE_SXS cookie = _Py_ActivateActCtx(); #endif /* We use LoadLibraryEx so Windows looks for dependent DLLs in directory of pathname first. */ /* XXX This call doesn't exist in Windows CE */ hDLL = LoadLibraryExW(wpathname, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); #if HAVE_SXS _Py_DeactivateActCtx(cookie); #endif /* restore old error mode settings */ SetErrorMode(old_mode); if (hDLL==NULL){ PyObject *message; unsigned int errorCode; /* Get an error string from Win32 error code */ wchar_t theInfo[256]; /* Pointer to error text from system */ int theLength; /* Length of error text */ errorCode = GetLastError(); theLength = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ NULL, /* message source */ errorCode, /* the message (error) ID */ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ theInfo, /* the buffer */ sizeof(theInfo), /* the buffer size */ NULL); /* no additional format args. */ /* Problem: could not get the error message. This should not happen if called correctly. */ if (theLength == 0) { message = PyUnicode_FromFormat( "DLL load failed with error code %d", errorCode); } else { /* For some reason a \r\n is appended to the text */ if (theLength >= 2 && theInfo[theLength-2] == '\r' && theInfo[theLength-1] == '\n') { theLength -= 2; theInfo[theLength] = '\0'; } message = PyUnicode_FromString( "DLL load failed: "); PyUnicode_AppendAndDel(&message, PyUnicode_FromWideChar( theInfo, theLength)); } if (message != NULL) { PyErr_SetImportError(message, PyUnicode_FromString(shortname), pathname); Py_DECREF(message); } return NULL; } else { char buffer[256]; PyOS_snprintf(buffer, sizeof(buffer), #ifdef _DEBUG "python%d%d_d.dll", #else "python%d%d.dll", #endif PY_MAJOR_VERSION,PY_MINOR_VERSION); import_python = GetPythonImport(hDLL); if (import_python && strcasecmp(buffer,import_python)) { PyErr_Format(PyExc_ImportError, "Module use of %.150s conflicts " "with this version of Python.", import_python); FreeLibrary(hDLL); return NULL; } } p = GetProcAddress(hDLL, funcname); } return p; }
/** 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; }
bool PrepareAndBind(Cursor* cur, PyObject* pSql, PyObject* original_params, bool skip_first) { // // Normalize the parameter variables. // // Since we may replace parameters (we replace objects with Py_True/Py_False when writing to a bit/bool column), // allocate an array and use it instead of the original sequence. Since we don't change ownership we don't bother // with incref. (That is, PySequence_GetItem will INCREF and ~ObjectArrayHolder will DECREF.) int params_offset = skip_first ? 1 : 0; Py_ssize_t cParams = original_params == 0 ? 0 : PySequence_Length(original_params) - params_offset; PyObject** params = (PyObject**)malloc(sizeof(PyObject*) * cParams); if (!params) { PyErr_NoMemory(); return 0; } for (Py_ssize_t i = 0; i < cParams; i++) params[i] = PySequence_GetItem(original_params, i + params_offset); ObjectArrayHolder holder(cParams, params); // // Prepare the SQL if necessary. // if (pSql == cur->pPreparedSQL) { // We've already prepared this SQL, so we don't need to do so again. We've also cached the parameter // information in cur->paramdescs. if (cParams != cur->paramcount) { RaiseErrorV(0, ProgrammingError, "The SQL contains %d parameter markers, but %d parameters were supplied", cur->paramcount, cParams); return false; } } else { FreeParameterInfo(cur); SQLRETURN ret; if (PyString_Check(pSql)) { Py_BEGIN_ALLOW_THREADS ret = SQLPrepare(cur->hstmt, (SQLCHAR*)PyString_AS_STRING(pSql), SQL_NTS); Py_END_ALLOW_THREADS } else { Py_BEGIN_ALLOW_THREADS ret = SQLPrepareW(cur->hstmt, (SQLWCHAR*)PyUnicode_AsUnicode(pSql), SQL_NTS); Py_END_ALLOW_THREADS } if (cur->cnxn->hdbc == SQL_NULL_HANDLE) { // The connection was closed by another thread in the ALLOW_THREADS block above. RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); return false; } if (!SQL_SUCCEEDED(ret)) { RaiseErrorFromHandle("SQLPrepare", GetConnection(cur)->hdbc, cur->hstmt); return false; } if (!CacheParamDesc(cur)) return false; cur->pPreparedSQL = pSql; Py_INCREF(cur->pPreparedSQL); }
/* Calculate new record length or append field to record. Return new * record length. */ static int join_append_data(WriterObj *self, Py_UNICODE *field, int quote_empty, int *quoted, int copy_phase) { DialectObj *dialect = self->dialect; int i; int rec_len; Py_UNICODE *lineterm; #define ADDCH(c) \ do {\ if (copy_phase) \ self->rec[rec_len] = c;\ rec_len++;\ } while(0) lineterm = PyUnicode_AsUnicode(dialect->lineterminator); if (lineterm == NULL) return -1; rec_len = self->rec_len; /* If this is not the first field we need a field separator */ if (self->num_fields > 0) ADDCH(dialect->delimiter); /* Handle preceding quote */ if (copy_phase && *quoted) ADDCH(dialect->quotechar); /* Copy/count field data */ /* If field is null just pass over */ for (i = 0; field; i++) { Py_UNICODE c = field[i]; int want_escape = 0; if (c == '\0') break; if (c == dialect->delimiter || c == dialect->escapechar || c == dialect->quotechar || Py_UNICODE_strchr(lineterm, c)) { if (dialect->quoting == QUOTE_NONE) want_escape = 1; else { if (c == dialect->quotechar) { if (dialect->doublequote) ADDCH(dialect->quotechar); else want_escape = 1; } if (!want_escape) *quoted = 1; } if (want_escape) { if (!dialect->escapechar) { PyErr_Format(error_obj, "need to escape, but no escapechar set"); return -1; } ADDCH(dialect->escapechar); } } /* Copy field character into record buffer. */ ADDCH(c); } /* If field is empty check if it needs to be quoted. */ if (i == 0 && quote_empty) { if (dialect->quoting == QUOTE_NONE) { PyErr_Format(error_obj, "single empty field record must be quoted"); return -1; } else *quoted = 1; } if (*quoted) { if (copy_phase) ADDCH(dialect->quotechar); else rec_len += 2; } return rec_len; #undef ADDCH }
bool AllocateMore(SQLLEN cbAdd) { // cbAdd // The number of bytes (cb --> count of bytes) to add. if (cbAdd == 0) return true; SQLLEN newSize = bufferSize + cbAdd; if (usingStack) { // This is the first call and `buffer` points to stack memory. Allocate a new object and copy the stack // data into it. char* stackBuffer = buffer; if (dataType == SQL_C_CHAR) { bufferOwner = PyBytes_FromStringAndSize(0, newSize); buffer = bufferOwner ? PyBytes_AS_STRING(bufferOwner) : 0; } else if (dataType == SQL_C_BINARY) { #if PY_VERSION_HEX >= 0x02060000 bufferOwner = PyByteArray_FromStringAndSize(0, newSize); buffer = bufferOwner ? PyByteArray_AS_STRING(bufferOwner) : 0; #else bufferOwner = PyBytes_FromStringAndSize(0, newSize); buffer = bufferOwner ? PyBytes_AS_STRING(bufferOwner) : 0; #endif } else if (sizeof(SQLWCHAR) == Py_UNICODE_SIZE) { // Allocate directly into a Unicode object. bufferOwner = PyUnicode_FromUnicode(0, newSize / element_size); buffer = bufferOwner ? (char*)PyUnicode_AsUnicode(bufferOwner) : 0; } else { // We're Unicode, but SQLWCHAR and Py_UNICODE don't match, so maintain our own SQLWCHAR buffer. bufferOwner = 0; buffer = (char*)pyodbc_malloc((size_t)newSize); } if (buffer == 0) return false; usingStack = false; memcpy(buffer, stackBuffer, (size_t)bufferSize); bufferSize = newSize; return true; } if (bufferOwner && PyUnicode_CheckExact(bufferOwner)) { if (PyUnicode_Resize(&bufferOwner, newSize / element_size) == -1) return false; buffer = (char*)PyUnicode_AsUnicode(bufferOwner); } #if PY_VERSION_HEX >= 0x02060000 else if (bufferOwner && PyByteArray_CheckExact(bufferOwner)) { if (PyByteArray_Resize(bufferOwner, newSize) == -1) return false; buffer = PyByteArray_AS_STRING(bufferOwner); } #else else if (bufferOwner && PyBytes_CheckExact(bufferOwner)) { if (_PyBytes_Resize(&bufferOwner, newSize) == -1) return false; buffer = PyBytes_AS_STRING(bufferOwner); } #endif else { char* tmp = (char*)realloc(buffer, (size_t)newSize); if (tmp == 0) return false; buffer = tmp; } bufferSize = newSize; return true; }
Py_UNICODE* JPyString::AsUnicode(PyObject* obj) { return PyUnicode_AsUnicode(obj); }
/* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":95 */ ((struct __pyx_obj_17_pymfclib_winhttp_WinHTTPSession *)__pyx_v_self)->hInternet = NULL; goto __pyx_L2; } __pyx_L2:; Py_DECREF(__pyx_v_self); } static PyObject *__pyx_f_17_pymfclib_winhttp_14WinHTTPSession_getProxyForUrl(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_17_pymfclib_winhttp_14WinHTTPSession_getProxyForUrl(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_url = 0; PyObject *__pyx_v_configurl = 0; WINHTTP_AUTOPROXY_OPTIONS __pyx_v_autoopt; WINHTTP_PROXY_INFO __pyx_v_proxyinfo; struct __pyx_obj_17_pymfclib_winhttp_ProxyInfo *__pyx_v_ret; PyObject *__pyx_r; int __pyx_1; __pyx_t_17_pymfclib_winhttp_PYMFC_WCHAR *__pyx_2; BOOL __pyx_3; PyObject *__pyx_4 = 0; static char *__pyx_argnames[] = {"url","configurl",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OO", __pyx_argnames, &__pyx_v_url, &__pyx_v_configurl)) return 0; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_url); Py_INCREF(__pyx_v_configurl); __pyx_v_ret = ((struct __pyx_obj_17_pymfclib_winhttp_ProxyInfo *)Py_None); Py_INCREF(Py_None); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":102 */ memset((&__pyx_v_autoopt),0,(sizeof(__pyx_v_autoopt))); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":103 */ memset((&__pyx_v_proxyinfo),0,(sizeof(__pyx_v_proxyinfo))); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":105 */ __pyx_1 = PyObject_IsTrue(__pyx_v_configurl); if (__pyx_1 < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; goto __pyx_L1;} if (__pyx_1) { /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":106 */ __pyx_v_autoopt.dwFlags = (WINHTTP_AUTOPROXY_AUTO_DETECT | WINHTTP_AUTOPROXY_CONFIG_URL); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":107 */ __pyx_2 = PyUnicode_AsUnicode(__pyx_v_configurl); if (__pyx_2 == NULL) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; goto __pyx_L1;} __pyx_v_autoopt.lpszAutoConfigUrl = __pyx_2; goto __pyx_L2; } /*else*/ { __pyx_v_autoopt.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; } __pyx_L2:; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":111 */ __pyx_v_autoopt.dwAutoDetectFlags = (WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":112 */ __pyx_v_autoopt.fAutoLogonIfChallenged = 1; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":114 */ __pyx_2 = PyUnicode_AsUnicode(__pyx_v_url); if (__pyx_2 == NULL) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; goto __pyx_L1;} __pyx_3 = WinHttpGetProxyForUrl(((struct __pyx_obj_17_pymfclib_winhttp_WinHTTPSession *)__pyx_v_self)->hInternet,__pyx_2,(&__pyx_v_autoopt),(&__pyx_v_proxyinfo)); if (__pyx_3) { /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":115 */ __pyx_4 = PyObject_CallObject(((PyObject *)__pyx_ptype_17_pymfclib_winhttp_ProxyInfo), 0); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; goto __pyx_L1;} Py_DECREF(((PyObject *)__pyx_v_ret)); __pyx_v_ret = ((struct __pyx_obj_17_pymfclib_winhttp_ProxyInfo *)__pyx_4); __pyx_4 = 0; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":116 */ __pyx_4 = PyInt_FromLong((__pyx_v_proxyinfo.dwAccessType == WINHTTP_ACCESS_TYPE_NO_PROXY)); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; goto __pyx_L1;} Py_DECREF(__pyx_v_ret->noproxy); __pyx_v_ret->noproxy = __pyx_4; __pyx_4 = 0; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":118 */ /*try:*/ { /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":119 */ __pyx_1 = (__pyx_v_proxyinfo.lpszProxy != 0); if (__pyx_1) { __pyx_4 = _fromWideChar(__pyx_v_proxyinfo.lpszProxy); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; goto __pyx_L5;} Py_DECREF(__pyx_v_ret->proxy); __pyx_v_ret->proxy = __pyx_4; __pyx_4 = 0; goto __pyx_L7; } __pyx_L7:; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":121 */ __pyx_1 = (__pyx_v_proxyinfo.lpszProxyBypass != 0); if (__pyx_1) { __pyx_4 = _fromWideChar(__pyx_v_proxyinfo.lpszProxyBypass); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; goto __pyx_L5;} Py_DECREF(__pyx_v_ret->proxybypass); __pyx_v_ret->proxybypass = __pyx_4; __pyx_4 = 0; goto __pyx_L8; } __pyx_L8:; } /*finally:*/ { int __pyx_why; PyObject *__pyx_exc_type, *__pyx_exc_value, *__pyx_exc_tb; int __pyx_exc_lineno; __pyx_why = 0; goto __pyx_L6; __pyx_L5: { __pyx_why = 4; Py_XDECREF(__pyx_4); __pyx_4 = 0; PyErr_Fetch(&__pyx_exc_type, &__pyx_exc_value, &__pyx_exc_tb); __pyx_exc_lineno = __pyx_lineno; goto __pyx_L6; } __pyx_L6:; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":124 */ __pyx_1 = (__pyx_v_proxyinfo.lpszProxy != 0); if (__pyx_1) { GlobalFree(__pyx_v_proxyinfo.lpszProxy); goto __pyx_L10; } __pyx_L10:; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":126 */ __pyx_1 = (__pyx_v_proxyinfo.lpszProxyBypass != 0); if (__pyx_1) { GlobalFree(__pyx_v_proxyinfo.lpszProxyBypass); goto __pyx_L11; } __pyx_L11:; switch (__pyx_why) { case 4: { PyErr_Restore(__pyx_exc_type, __pyx_exc_value, __pyx_exc_tb); __pyx_lineno = __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; goto __pyx_L1; } } } /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":128 */ Py_INCREF(((PyObject *)__pyx_v_ret)); __pyx_r = ((PyObject *)__pyx_v_ret); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_4); __Pyx_AddTraceback("_pymfclib_winhttp.WinHTTPSession.getProxyForUrl"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_ret); Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_url); Py_DECREF(__pyx_v_configurl); return __pyx_r; }
// Returns a new string MCHAR * pythonExceptionTraceback( bool clearException ) { /* import traceback return '\n'.join(traceback.format_exc()).encode('ascii','replace') */ MCHAR * ret = 0; bool success = false; PyObject * type, * value, * traceback; /* Save the current exception */ PyErr_Fetch(&type, &value, &traceback); if( type ) { PyObject * traceback_module = PyImport_ImportModule("traceback"); if (traceback_module) { /* Call the traceback module's format_exception function, which returns a list */ PyObject * traceback_list = PyObject_CallMethod(traceback_module, "format_exception", "OOO", type, value ? value : Py_None, traceback ? traceback : Py_None); if( traceback_list ) { PyObject * separator = PyString_FromString(""); if( separator ) { PyObject * retUni = PyUnicode_Join(separator, traceback_list); if( retUni ) { #ifdef UNICODE ret = _tcsdup( PyUnicode_AsUnicode(retUni) ); #else PyObject * retAscii = PyUnicode_AsEncodedString(retUni, "ascii", "replace"); if( retAscii ) { Py_ssize_t len = 0; char * tmp; if( PyString_AsStringAndSize( retAscii, &tmp, &len ) != -1 ) { ret = strdup( tmp );//, len ); success = true; } else { ret = _tcsdup( _T("Uhoh, failed to get pointer to ascii representation of the exception") ); success = false; } Py_DECREF( retAscii ); } else { ret = _tcsdup( _T("Uhoh, encoding exception to ascii failed") ); success = false; } #endif Py_DECREF(retUni); } else ret = _tcsdup(_T("PyUnicode_Join failed")); Py_DECREF(separator); } else ret = _tcsdup(_T("PyUnicode_FromString failed")); Py_DECREF(traceback_list); } else ret = _tcsdup(_T("Failure calling traceback.format_exception")); Py_DECREF(traceback_module); } else ret = _tcsdup(_T("Unable to load the traceback module, can't get exception text")); } else ret = _tcsdup(_T("pythonExceptionTraceback called, but no exception set")); if( clearException ) { Py_DECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); } else PyErr_Restore(type,value,traceback); return ret; }
bool AllocateMore(SQLLEN cbAdd) { if (cbAdd == 0) return true; SQLLEN newSize = bufferSize + cbAdd; if (usingStack) { // This is the first call and `buffer` points to stack memory. Allocate a new object and copy the stack // data into it. char* stackBuffer = buffer; if (dataType == SQL_C_CHAR || dataType == SQL_C_BINARY) { bufferOwner = PyString_FromStringAndSize(0, newSize); buffer = bufferOwner ? PyString_AS_STRING(bufferOwner) : 0; } else if (sizeof(wchar_t) == Py_UNICODE_SIZE) { // Allocate directly into a Unicode object. bufferOwner = PyUnicode_FromUnicode(0, newSize / element_size); buffer = bufferOwner ? (char*)PyUnicode_AsUnicode(bufferOwner) : 0; } else { // We're Unicode, but wchar_t and Py_UNICODE don't match, so maintain our own wchar_t buffer. buffer = (char*)malloc(newSize); } usingStack = false; if (buffer == 0) return false; memcpy(buffer, stackBuffer, bufferSize); bufferSize = newSize; return true; } if (PyString_CheckExact(bufferOwner)) { if (_PyString_Resize(&bufferOwner, newSize) == -1) return false; buffer = PyString_AS_STRING(bufferOwner); } else if (PyUnicode_CheckExact(bufferOwner)) { if (PyUnicode_Resize(&bufferOwner, newSize / element_size) == -1) return false; buffer = (char*)PyUnicode_AsUnicode(bufferOwner); } else { char* tmp = (char*)realloc(buffer, newSize); if (tmp == 0) return false; buffer = tmp; } bufferSize = newSize; return true; }
//--------------------------------------------------------------------------- template<> std::wstring FromPyObject<std::wstring>(PyObject *O) { return PyUnicode_AsUnicode(O); }
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; }
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!"); }
/* * 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; }