/* ** Convert objects from Python to CoreFoundation and vice-versa. */ #include #include "Python.h" #include "pymactoolbox.h" #include "pycfbridge.h" /* ---------------------------------------- */ /* CoreFoundation objects to Python objects */ /* ---------------------------------------- */ PyObject * PyCF_CF2Python(CFTypeRef src) { CFTypeID typeid; if( src == NULL ) { Py_INCREF(Py_None); return Py_None; } typeid = CFGetTypeID(src); if (typeid == CFArrayGetTypeID()) return PyCF_CF2Python_sequence((CFArrayRef)src); if (typeid == CFDictionaryGetTypeID()) return PyCF_CF2Python_mapping((CFDictionaryRef)src); return PyCF_CF2Python_simple(src); } PyObject * PyCF_CF2Python_sequence(CFArrayRef src) { int size = CFArrayGetCount(src); PyObject *rv; CFTypeRef item_cf; PyObject *item_py = NULL; int i; if ( (rv=PyList_New(size)) == NULL ) return NULL; for(i=0; iob_type->tp_name); return 0; } size = PySequence_Size(src); rv = CFArrayCreateMutable((CFAllocatorRef)NULL, size, &kCFTypeArrayCallBacks); if (rv == NULL) { PyMac_Error(resNotFound); goto err; } for( i=0; iob_type->tp_name); return 0; } size = PyMapping_Size(src); rv = CFDictionaryCreateMutable((CFAllocatorRef)NULL, size, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (rv == NULL) { PyMac_Error(resNotFound); goto err; } if ( (aslist = PyMapping_Items(src)) == NULL ) goto err; for( i=0; iob_type->tp_name); return 0; } int PyCF_Python2CF_string(PyObject *src, CFStringRef *dst) { char *chars; CFIndex size; UniChar *unichars; if (PyString_Check(src)) { if (!PyArg_Parse(src, "es", "ascii", &chars)) return 0; /* This error is more descriptive than the general one below */ *dst = CFStringCreateWithCString((CFAllocatorRef)NULL, chars, kCFStringEncodingASCII); return 1; } if (PyUnicode_Check(src)) { /* We use the CF types here, if Python was configured differently that will give an error */ size = PyUnicode_GetSize(src); if ((unichars = PyUnicode_AsUnicode(src)) == NULL ) goto err; *dst = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size); return 1; } err: PyErr_Format(PyExc_TypeError, "Cannot convert %.500s objects to CFString", src->ob_type->tp_name); return 0; }