Beispiel #1
0
static GnmFuncHelp const *
python_function_get_gnumeric_help (PyObject *python_fn_info_dict, PyObject *python_fn,
                                   const gchar *fn_name)
{
	gchar *help_attr_name;
	PyObject *cobject_help_value;

	help_attr_name = g_strdup_printf ("_CGnumericHelp_%s", fn_name);
	cobject_help_value = PyDict_GetItemString (python_fn_info_dict, help_attr_name);

	if (cobject_help_value == NULL) {
		PyObject *python_fn_help = ((PyFunctionObject *) python_fn)->func_doc;
		if (python_fn_help != NULL && PyString_Check (python_fn_help)) {
			GnmFuncHelp *new_help = g_new (GnmFuncHelp, 2);
			int i = 0;

#if 0
			new_help[i].type = GNM_FUNC_HELP_OLD;
			new_help[i].text = PyString_AsString (python_fn_help);
			i++;
#endif

			new_help[i].type = GNM_FUNC_HELP_END;
			new_help[i].text = NULL;
			i++;

			cobject_help_value = PyCObject_FromVoidPtr (new_help, &g_free);
			PyDict_SetItemString (python_fn_info_dict, help_attr_name, cobject_help_value);
		}
	}
	g_free (help_attr_name);
	if (cobject_help_value == NULL)
		return NULL;

	return (GnmFuncHelp const *) PyCObject_AsVoidPtr (cobject_help_value);
}
Beispiel #2
0
PyObject *xmlsec_TransformExclC14NWithCommentsId(PyObject *self, PyObject *args) {
  return PyCObject_FromVoidPtr((void *) xmlSecTransformExclC14NWithCommentsId, NULL);
}
// Parse a Python object as a sequence of either QVector[234]D instances or a
// sequence of sequence of floats and return an array that can be passed to
// QGLShaderProgram::setAttributeArray().  The array is destroyed only when the
// shader is garbage collected or when replaced by another array.
const GLfloat *qpyopengl_attribute_array(PyObject *values, PyObject *shader,
        PyObject *key, int *tsize, sipErrorState *estate)
{
    // Check the key was created correctly.
    if (!key)
    {
        *estate = sipErrorFail;
        return 0;
    }

    // Get the dict that holds the converted arrays.
    PyObject *dict = ((sipSimpleWrapper *)shader)->user;

    if (!dict)
    {
        dict = PyDict_New();

        if (!dict)
        {
            Py_DECREF(key);

            *estate = sipErrorFail;
            return 0;
        }

        ((sipSimpleWrapper *)shader)->user = dict;
    }

    // Check that values is a non-empty sequence.
    values = PySequence_Fast(values, "an attribute array must be a sequence");

    if (!values)
    {
        Py_DECREF(key);

        *estate = sipErrorContinue;
        return 0;
    }

    SIP_SSIZE_T nr_items = PySequence_Fast_GET_SIZE(values);

    if (nr_items < 1)
    {
        PyErr_SetString(PyExc_TypeError,
                "an attribute array must have at least one element");

        Py_DECREF(key);
        Py_DECREF(values);

        *estate = sipErrorFail;
        return 0;
    }

    // The first element determines the type expected.
    PyObject *itm = PySequence_Fast_GET_ITEM(values, 0);

    const sipTypeDef *td;
    SIP_SSIZE_T nr_dim;

    if (sipCanConvertToType(itm, sipType_QVector2D, SIP_NOT_NONE))
    {
        td = sipType_QVector2D;
        nr_dim = 2;
    }
    else if (sipCanConvertToType(itm, sipType_QVector3D, SIP_NOT_NONE))
    {
        td = sipType_QVector3D;
        nr_dim = 3;
    }
    else if (sipCanConvertToType(itm, sipType_QVector4D, SIP_NOT_NONE))
    {
        td = sipType_QVector4D;
        nr_dim = 4;
    }
    else if (PySequence_Check(itm) && (nr_dim = PySequence_Size(itm)) >= 1)
    {
        td = 0;
    }
    else
    {
        PyErr_SetString(PyExc_TypeError,
                "an attribute array must be a sequence of QVector2D, "
                "QVector3D, QVector4D, or a sequence of sequences of floats");

        Py_DECREF(key);
        Py_DECREF(values);

        *estate = sipErrorFail;
        return 0;
    }

    // Create the array that will be returned.
    GLfloat *array = new GLfloat[nr_items * nr_dim];

    // Convert the values.
    GLfloat *ap = array;

    for (SIP_SSIZE_T i = 0; i < nr_items; ++i)
    {
        int iserr = 0;

        itm = PySequence_Fast_GET_ITEM(values, i);

        if (td)
        {
            void *cpp;

            cpp = sipForceConvertToType(itm, td, 0,
                    SIP_NOT_NONE | SIP_NO_CONVERTORS, 0, &iserr);

            if (iserr)
            {
                PyErr_Format(PyExc_TypeError,
                        "attribute array elements should all be '%s', not '%s'",
                        sipTypeAsPyTypeObject(td)->tp_name,
                        Py_TYPE(itm)->tp_name);
            }
            else if (td == sipType_QVector2D)
            {
                QVector2D *v = reinterpret_cast<QVector2D *>(cpp);

                *ap++ = v->x();
                *ap++ = v->y();
            }
            else if (td == sipType_QVector3D)
            {
                QVector3D *v = reinterpret_cast<QVector3D *>(cpp);

                *ap++ = v->x();
                *ap++ = v->y();
                *ap++ = v->z();
            }
            else if (td == sipType_QVector4D)
            {
                QVector4D *v = reinterpret_cast<QVector4D *>(cpp);

                *ap++ = v->x();
                *ap++ = v->y();
                *ap++ = v->z();
                *ap++ = v->w();
            }
        }
        else
        {
            itm = PySequence_Fast(itm,
                    "attribute array elements should all be sequences");

            if (itm)
            {
                if (PySequence_Fast_GET_SIZE(itm) != nr_dim)
                {
                    PyErr_Format(PyExc_TypeError,
                            "attribute array elements should all be sequences "
#if PY_VERSION_HEX >= 0x02050000
                            "of length %zd",
#else
                            "of length %d",
#endif
                            nr_dim);

                    Py_DECREF(itm);
                    iserr = 1;
                }
                else
                {
                    PyErr_Clear();

                    for (SIP_SSIZE_T j = 0; j < nr_dim; ++j)
                        *ap++ = PyFloat_AsDouble(
                                PySequence_Fast_GET_ITEM(itm, j));

                    if (PyErr_Occurred())
                    {
                        PyErr_SetString(PyExc_TypeError,
                                "attribute array elements should all be "
                                "sequences of floats");

                        Py_DECREF(itm);
                        iserr = 1;
                    }
                }
            }
            else
            {
                iserr = 1;
            }
        }

        if (iserr)
        {
            Py_DECREF(key);
            Py_DECREF(values);
            delete[] array;

            *estate = sipErrorFail;
            return 0;
        }
    }

    Py_DECREF(values);

    *tsize = nr_dim;

    // Wrap the array in a Python object so that it won't leak.
#if defined(SIP_USE_PYCAPSULE)
    PyObject *array_obj = PyCapsule_New(array, 0, array_dtor);
#else
    PyObject *array_obj = PyCObject_FromVoidPtr(array, array_dtor);
#endif

    if (!array_obj)
    {
        Py_DECREF(key);
        delete[] array;

        *estate = sipErrorFail;
        return 0;
    }

    int rc = PyDict_SetItem(dict, key, array_obj);

    Py_DECREF(key);
    Py_DECREF(array_obj);

    if (rc < 0)
    {
        *estate = sipErrorFail;
        return 0;
    }

    return array;
}
Beispiel #4
0
/*
 * Implement ascobject() for the type.
 */
static PyObject *sipVoidPtr_ascobject(sipVoidPtrObject *v, PyObject *arg)
{
    return PyCObject_FromVoidPtr(v->voidptr, NULL);
}
Beispiel #5
0
PyMODINIT_FUNC
init_ExtensionClass(void)
{
  PyObject *m, *s;

  if (pickle_setup() < 0)
    return;

#define DEFINE_STRING(S) \
  if(! (str ## S = PyString_FromString(# S))) return

  DEFINE_STRING(__of__);
  DEFINE_STRING(__get__);
  DEFINE_STRING(__class_init__);
  DEFINE_STRING(__init__);
  DEFINE_STRING(__bases__);
  DEFINE_STRING(__mro__);
  DEFINE_STRING(__new__);
#undef DEFINE_STRING

  PyExtensionClassCAPI = &TrueExtensionClassCAPI;

  ExtensionClassType.ob_type = &PyType_Type;
  ExtensionClassType.tp_base = &PyType_Type;
  ExtensionClassType.tp_basicsize = PyType_Type.tp_basicsize;
  ExtensionClassType.tp_traverse = PyType_Type.tp_traverse;
  ExtensionClassType.tp_clear = PyType_Type.tp_clear;
  
  /* Initialize types: */
  if (PyType_Ready(&ExtensionClassType) < 0)
    return;

  BaseType.ob_type = &ExtensionClassType;
  BaseType.tp_base = &PyBaseObject_Type;
  BaseType.tp_basicsize = PyBaseObject_Type.tp_basicsize;
  BaseType.tp_new = PyType_GenericNew;

  if (PyType_Ready(&BaseType) < 0)
    return;

  NoInstanceDictionaryBaseType.ob_type = &ExtensionClassType;
  NoInstanceDictionaryBaseType.tp_base = &BaseType;
  NoInstanceDictionaryBaseType.tp_basicsize = BaseType.tp_basicsize;
  NoInstanceDictionaryBaseType.tp_new = PyType_GenericNew;

  if (PyType_Ready(&NoInstanceDictionaryBaseType) < 0)
    return;
  
  /* Create the module and add the functions */
  m = Py_InitModule3("_ExtensionClass", ec_methods,
                     _extensionclass_module_documentation);

  if (m == NULL)
    return;

  s = PyCObject_FromVoidPtr(PyExtensionClassCAPI, NULL);
  if (PyModule_AddObject(m, "CAPI2", s) < 0)
    return;
        
  /* Add types: */
  if (PyModule_AddObject(m, "ExtensionClass", 
                         (PyObject *)&ExtensionClassType) < 0)
    return;
  if (PyModule_AddObject(m, "Base", (PyObject *)&BaseType) < 0)
    return;
  if (PyModule_AddObject(m, "NoInstanceDictionaryBase", 
                         (PyObject *)&NoInstanceDictionaryBaseType) < 0)
    return;
}
Beispiel #6
0
PyObject* wrapQObject(QObject* obj)
{
	return PyCObject_FromVoidPtr((void*)obj, NULL);
}
static PyObject*
module_init(void)
{
    PyObject *module, *ts_module, *capi;
    PyObject *copy_reg;

    if (init_strings() < 0)
        return NULL;

#ifdef PY3K
    module = PyModule_Create(&moduledef);
#else
    module = Py_InitModule3("cPersistence", cPersistence_methods,
                            cPersistence_doc_string);
#endif

#ifdef PY3K
    ((PyObject*)&Pertype)->ob_type = &PyType_Type;
#else
    Pertype.ob_type = &PyType_Type;
#endif
    Pertype.tp_new = PyType_GenericNew;
    if (PyType_Ready(&Pertype) < 0)
        return NULL;
    if (PyModule_AddObject(module, "Persistent", (PyObject *)&Pertype) < 0)
        return NULL;

    cPersistenceCAPI = &truecPersistenceCAPI;
#ifdef PY3K
    capi = PyCapsule_New(cPersistenceCAPI, CAPI_CAPSULE_NAME, NULL);
#else
    capi = PyCObject_FromVoidPtr(cPersistenceCAPI, NULL);
#endif
    if (!capi)
        return NULL;
    if (PyModule_AddObject(module, "CAPI", capi) < 0)
        return NULL;

    if (PyModule_AddIntConstant(module, "GHOST", cPersistent_GHOST_STATE) < 0)
        return NULL;

    if (PyModule_AddIntConstant(module, "UPTODATE",
                                cPersistent_UPTODATE_STATE) < 0)
        return NULL;

    if (PyModule_AddIntConstant(module, "CHANGED",
                                cPersistent_CHANGED_STATE) < 0)
        return NULL;

    if (PyModule_AddIntConstant(module, "STICKY",
                                cPersistent_STICKY_STATE) < 0)
        return NULL;

    py_simple_new = PyObject_GetAttrString(module, "simple_new");
    if (!py_simple_new)
        return NULL;

#ifdef PY3K
    copy_reg = PyImport_ImportModule("copyreg");
#else
    copy_reg = PyImport_ImportModule("copy_reg");
#endif
    if (!copy_reg)
        return NULL;

    copy_reg_slotnames = PyObject_GetAttrString(copy_reg, "_slotnames");
    if (!copy_reg_slotnames)
    {
      Py_DECREF(copy_reg);
      return NULL;
    }

    __newobj__ = PyObject_GetAttrString(copy_reg, "__newobj__");
    if (!__newobj__)
    {
      Py_DECREF(copy_reg);
      return NULL;
    }

    if (!TimeStamp)
    {
      ts_module = PyImport_ImportModule("persistent.timestamp");
      if (!ts_module)
        return NULL;
      TimeStamp = PyObject_GetAttrString(ts_module, "TimeStamp");
      Py_DECREF(ts_module);
      /* fall through to immediate return on error */
    }
    return module;
}
Beispiel #8
0
static PyObject *PyPCAP_next(PyPCAP *self) {
  PyObject *result;
  int len;
  int packet_offset;

  // Make sure our buffer is full enough:
  if(self->buffer->size - self->buffer->readptr < MAX_PACKET_SIZE) {
    len = PyPCAP_fill_buffer(self, self->fd);
    
    if(len<0) return NULL;
  };

  packet_offset = self->buffer->readptr;

  /** This is an interesting side effect of the talloc reference model:
      
  talloc_reference(context, ptr) adds a new context to ptr so ptr is
  now effectively parented by two parents. The two parents are not
  equal however because a talloc free(ptr) will remove the reference
  first and then the original parent.

  This causes problems here because we create the packet_header with
  self->buffer as a context. However other code takes references to it
  - pinning it to other parents. If we did a
  talloc_free(self->packet_header) here we would be removing those
  references _instead_ of freeing the ptr from our own self->buffer
  reference. This will cause both memory leaks (because we will not be
  freeing packet_header at all, and later crashes because important
  references will be removed.

  When references begin to be used extensively I think we need to
  start using talloc_unlink instead of talloc_free everywhere.
  */
  // Free old packets:
  if(self->packet_header) 
    talloc_unlink(self->buffer, self->packet_header);

  // Make a new packet:
  self->packet_header = (PcapPacketHeader)CONSTRUCT(PcapPacketHeader, Packet,
						    super.Con, self->buffer, NULL);

  if(self->file_header->little_endian) {
    self->packet_header->super.format = self->packet_header->le_format;
  };

  // Read the packet in:
  len = self->packet_header->super.Read((Packet)self->packet_header, self->buffer);

  // Did we finish?
  if(len<=0) {
    return PyErr_Format(PyExc_StopIteration, "Done");
  };

  // Make sure the new packet knows its offset and where it came from:
  self->packet_header->header.offset = self->pcap_offset;
  self->packet_header->header.pcap_file_id = self->pcap_file_id;

  // Keep track of our own file offset:
  self->pcap_offset += self->buffer->readptr - packet_offset;
  // CALL(self->buffer, skip, self->buffer->readptr);

  // Adjust the output endianess if needed
  switch(self->output_format) {
  case FORCE_BIG_ENDIAN:
    // FIXME - Leaks!!!
    self->packet_header->super.format = PCAP_PKTHEADER_STRUCT;
    break;

  case FORCE_LITTLE_ENDIAN:
    self->packet_header->super.format = PCAP_PKTHEADER_STRUCT_LE;
    break;

  default:
    // Do nothing
    break;
  };

  // create a new pypacket object:
  result = PyObject_CallMethod(g_pypacket_module, "PyPacket", "N",
			       PyCObject_FromVoidPtr(self->packet_header,NULL), "PcapPacketHeader");

  return result;
};
Beispiel #9
0
PyObject* Mesh_Python_New( PyObject* self, PyObject* args ) {
    return PyCObject_FromVoidPtr( Mesh_New(), 0 );
}
Beispiel #10
0
PyObject *Node_instance(PyObject *i_s, PyObject *i_oArgs)
{
	bind_node *l_oFils = bind_node::instance();
	return PyCObject_FromVoidPtr(l_oFils, NULL);
}
static void python_process_event(int cpu, void *data,
				 int size __unused,
				 unsigned long long nsecs, char *comm)
{
	PyObject *handler, *retval, *context, *t, *obj, *dict = NULL;
	static char handler_name[256];
	struct format_field *field;
	unsigned long long val;
	unsigned long s, ns;
	struct event *event;
	unsigned n = 0;
	int type;
	int pid;

	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	type = trace_parse_common_type(data);

	event = find_cache_event(type);
	if (!event)
		die("ug! no event found for type %d", type);

	pid = trace_parse_common_pid(data);

	sprintf(handler_name, "%s__%s", event->system, event->name);

	handler = PyDict_GetItemString(main_dict, handler_name);
	if (handler && !PyCallable_Check(handler))
		handler = NULL;
	if (!handler) {
		dict = PyDict_New();
		if (!dict)
			Py_FatalError("couldn't create Python dict");
	}
	s = nsecs / NSECS_PER_SEC;
	ns = nsecs - s * NSECS_PER_SEC;

	scripting_context->event_data = data;

	context = PyCObject_FromVoidPtr(scripting_context, NULL);

	PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
	PyTuple_SetItem(t, n++,
			PyCObject_FromVoidPtr(scripting_context, NULL));

	if (handler) {
		PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
		PyTuple_SetItem(t, n++, PyInt_FromLong(s));
		PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
		PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
		PyTuple_SetItem(t, n++, PyString_FromString(comm));
	} else {
		PyDict_SetItemString(dict, "common_cpu", PyInt_FromLong(cpu));
		PyDict_SetItemString(dict, "common_s", PyInt_FromLong(s));
		PyDict_SetItemString(dict, "common_ns", PyInt_FromLong(ns));
		PyDict_SetItemString(dict, "common_pid", PyInt_FromLong(pid));
		PyDict_SetItemString(dict, "common_comm", PyString_FromString(comm));
	}
	for (field = event->format.fields; field; field = field->next) {
		if (field->flags & FIELD_IS_STRING) {
			int offset;
			if (field->flags & FIELD_IS_DYNAMIC) {
				offset = *(int *)(data + field->offset);
				offset &= 0xffff;
			} else
				offset = field->offset;
			obj = PyString_FromString((char *)data + offset);
		} else { /* FIELD_IS_NUMERIC */
			val = read_size(data + field->offset, field->size);
			if (field->flags & FIELD_IS_SIGNED) {
				if ((long long)val >= LONG_MIN &&
				    (long long)val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromLongLong(val);
			} else {
				if (val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromUnsignedLongLong(val);
			}
		}
		if (handler)
			PyTuple_SetItem(t, n++, obj);
		else
			PyDict_SetItemString(dict, field->name, obj);

	}
	if (!handler)
		PyTuple_SetItem(t, n++, dict);

	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

	if (handler) {
		retval = PyObject_CallObject(handler, t);
		if (retval == NULL)
			handler_call_die(handler_name);
	} else {
		handler = PyDict_GetItemString(main_dict, "trace_unhandled");
		if (handler && PyCallable_Check(handler)) {

			retval = PyObject_CallObject(handler, t);
			if (retval == NULL)
				handler_call_die("trace_unhandled");
		}
		Py_DECREF(dict);
	}

	Py_DECREF(t);
}
Beispiel #12
0
static void python_process_tracepoint(struct perf_sample *sample,
				      struct perf_evsel *evsel,
				      struct thread *thread,
				      struct addr_location *al)
{
	PyObject *handler, *retval, *context, *t, *obj, *dict = NULL;
	static char handler_name[256];
	struct format_field *field;
	unsigned long long val;
	unsigned long s, ns;
	struct event_format *event;
	unsigned n = 0;
	int pid;
	int cpu = sample->cpu;
	void *data = sample->raw_data;
	unsigned long long nsecs = sample->time;
	const char *comm = thread__comm_str(thread);

	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	event = find_cache_event(evsel);
	if (!event)
		die("ug! no event found for type %d", (int)evsel->attr.config);

	pid = raw_field_value(event, "common_pid", data);

	sprintf(handler_name, "%s__%s", event->system, event->name);

	handler = PyDict_GetItemString(main_dict, handler_name);
	if (handler && !PyCallable_Check(handler))
		handler = NULL;
	if (!handler) {
		dict = PyDict_New();
		if (!dict)
			Py_FatalError("couldn't create Python dict");
	}
	s = nsecs / NSECS_PER_SEC;
	ns = nsecs - s * NSECS_PER_SEC;

	scripting_context->event_data = data;
	scripting_context->pevent = evsel->tp_format->pevent;

	context = PyCObject_FromVoidPtr(scripting_context, NULL);

	PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
	PyTuple_SetItem(t, n++, context);

	if (handler) {
		PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
		PyTuple_SetItem(t, n++, PyInt_FromLong(s));
		PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
		PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
		PyTuple_SetItem(t, n++, PyString_FromString(comm));
	} else {
		pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
		pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
		pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
		pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
		pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
	}
	for (field = event->format.fields; field; field = field->next) {
		if (field->flags & FIELD_IS_STRING) {
			int offset;
			if (field->flags & FIELD_IS_DYNAMIC) {
				offset = *(int *)(data + field->offset);
				offset &= 0xffff;
			} else
				offset = field->offset;
			obj = PyString_FromString((char *)data + offset);
		} else { /* FIELD_IS_NUMERIC */
			val = read_size(event, data + field->offset,
					field->size);
			if (field->flags & FIELD_IS_SIGNED) {
				if ((long long)val >= LONG_MIN &&
				    (long long)val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromLongLong(val);
			} else {
				if (val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromUnsignedLongLong(val);
			}
		}
		if (handler)
			PyTuple_SetItem(t, n++, obj);
		else
			pydict_set_item_string_decref(dict, field->name, obj);

	}
	if (!handler)
		PyTuple_SetItem(t, n++, dict);

	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

	if (handler) {
		retval = PyObject_CallObject(handler, t);
		if (retval == NULL)
			handler_call_die(handler_name);
	} else {
		handler = PyDict_GetItemString(main_dict, "trace_unhandled");
		if (handler && PyCallable_Check(handler)) {

			retval = PyObject_CallObject(handler, t);
			if (retval == NULL)
				handler_call_die("trace_unhandled");
		}
		Py_DECREF(dict);
	}

	Py_DECREF(t);
}
Beispiel #13
0
PyObject *xmlsec_TransformVisa3DHackId(PyObject *self, PyObject *args) {
  return PyCObject_FromVoidPtr((void *) xmlSecTransformVisa3DHackId, NULL);
}
Beispiel #14
0
PyObject *xmlsec_TransformRemoveXmlTagsC14NId(PyObject *self, PyObject *args) {
  return PyCObject_FromVoidPtr((void *) xmlSecTransformRemoveXmlTagsC14NId, NULL);
}
Beispiel #15
0
PyObject *xmlsec_TransformXPointerId(PyObject *self, PyObject *args) {
  return PyCObject_FromVoidPtr((void *) xmlSecTransformXPointerId, NULL);
}
Beispiel #16
0
static PyObject* image_get_c_methods( PyObject* self )
{
    return PyCObject_FromVoidPtr( (void*)&c_methods, NULL );
}
Beispiel #17
0
/**
 * Interface for AtkUtilClass->add_global_event_listener.
 */
static guint
_class_add_global_event_listener (GSignalEmissionHook listener,
                                  const gchar *event_type)
{
    PyObject *dict = NULL;
    PyObject *cb = NULL;
    PyObject *key = NULL;
    gchar **split = g_strsplit (event_type, ":", 3);

    debug ("_class_add_global_event_listener\n");

    if (!split)
        return 0;

    if (!_global_listeners)
    {
        _global_listeners = PyDict_New ();
        if (!_global_listeners)
            return 0;
    }

    if (!_global_signals)
    {
        _global_signals = PyDict_New ();
        if (!_global_signals)
            return 0;
    }

#ifdef DEBUG
    printf ("DEBUG: Installing handler for %s\n", event_type);
#endif

    /* Create the event mappings, which are used by the AtkObject system
     * and have to be implemented manually by the user.
     */
    if (strcmp ("window", split[0]) == 0)
    {
        g_strfreev (split); /* Free string. */

        /* Lookup matching dict. */
        dict = PyDict_GetItemString (_global_listeners, event_type);
        if (!dict)
        {
            dict = _add_listener_dict (event_type);
            if (!dict)
                return 0;
        }
            
        /* Add listener. */
        cb = PyCObject_FromVoidPtr (listener, NULL);
        key = PyInt_FromLong ((long) _global_listener_ids + 1);
        if (PyDict_SetItem (dict, key, cb) == -1)
        {
            Py_DECREF (cb);
            Py_DECREF (key);
            return 0;
        }
        Py_DECREF (cb);
        Py_DECREF (key);
    }
    else
    {
        /* Lookup matching dict. */
        gchar *str = g_strconcat (split[1], ":", split[2], NULL);
        g_strfreev (split);
        
        dict = PyDict_GetItemString (_global_listeners, str);
        if (!dict)
        {
            dict = _add_listener_dict (str);
            if (!dict)
            {
                g_free (str);
                return 0;
            }
        }
        g_free (str);

        /* Add listener. */
        cb = PyCObject_FromVoidPtr (listener, NULL);
        key = PyInt_FromLong ((long) _global_listener_ids + 1);
        if (PyDict_SetItem (dict, key, cb) == -1)
        {
            Py_DECREF (cb);
            Py_DECREF (key);
            return 0;
        }
        Py_DECREF (cb);
        Py_DECREF (key);
    }
    /* Increase id count upon successful addition. */
    _global_listener_ids++;
    return _global_listener_ids;
}
Beispiel #18
0
static PyObject* create_module (void) {

# if PY_VERSION_HEX >= 0x03000000
  PyObject* module = PyModule_Create(&module_definition);
  auto module_ = make_xsafe(module);
  const char* ret = "O";
# else
  PyObject* module = Py_InitModule3(BOB_EXT_MODULE_NAME, module_methods, module_docstr);
  const char* ret = "N";
# endif
  if (!module) return 0;

  if (PyModule_AddStringConstant(module, "__version__", BOB_EXT_MODULE_VERSION) < 0) return 0;
  if (!init_BobIpBaseGeomNorm(module)) return 0;
  if (!init_BobIpBaseFaceEyesNorm(module)) return 0;
  if (!init_BobIpBaseLBP(module)) return 0;
  if (!init_BobIpBaseLBPTop(module)) return 0;
  if (!init_BobIpBaseDCTFeatures(module)) return 0;
  if (!init_BobIpBaseTanTriggs(module)) return 0;
  if (!init_BobIpBaseGaussian(module)) return 0;
  if (!init_BobIpBaseMultiscaleRetinex(module)) return 0;
  if (!init_BobIpBaseWeightedGaussian(module)) return 0;
  if (!init_BobIpBaseSelfQuotientImage(module)) return 0;
  if (!init_BobIpBaseGaussianScaleSpace(module)) return 0;
  if (!init_BobIpBaseSIFT(module)) return 0;
  if (!init_BobIpBaseHOG(module)) return 0;
  if (!init_BobIpBaseGLCM(module)) return 0;
  if (!init_BobIpBaseWiener(module)) return 0;

#if HAVE_VLFEAT
  if (!init_BobIpBaseVLFEAT(module)) return 0;
#endif // HAVE_VLFEAT


  static void* PyBobIpBase_API[PyBobIpBase_API_pointers];

  /* exhaustive list of C APIs */

  /**************
   * Versioning *
   **************/

  PyBobIpBase_API[PyBobIpBase_APIVersion_NUM] = (void *)&PyBobIpBase_APIVersion;

  /********************************
   * Bindings for bob.ip.base.LBP *
   ********************************/

  PyBobIpBase_API[PyBobIpBaseLBP_Type_NUM] = (void *)&PyBobIpBaseLBP_Type;
  PyBobIpBase_API[PyBobIpBaseLBP_Check_NUM] = (void *)&PyBobIpBaseLBP_Check;
  PyBobIpBase_API[PyBobIpBaseLBP_Converter_NUM] = (void *)&PyBobIpBaseLBP_Converter;

#if PY_VERSION_HEX >= 0x02070000

  /* defines the PyCapsule */

  PyObject* c_api_object = PyCapsule_New((void *)PyBobIpBase_API,
      BOB_EXT_MODULE_PREFIX "." BOB_EXT_MODULE_NAME "._C_API", 0);

#else

  PyObject* c_api_object = PyCObject_FromVoidPtr((void *)PyBobIpBase_API, 0);

#endif

  if (!c_api_object) return 0;

  if (PyModule_AddObject(module, "_C_API", c_api_object) < 0) return 0;


  /* imports bob.ip.base's C-API dependencies */
  if (import_bob_blitz() < 0) return 0;
  if (import_bob_core_random() < 0) return 0;
  if (import_bob_core_logging() < 0) return 0;
  if (import_bob_io_base() < 0) return 0;
  if (import_bob_sp() < 0) return 0;

  return Py_BuildValue(ret, module);
}
Beispiel #19
0
PyMODINIT_FUNC
initMMTK_pose(void)
{
  PyObject *m, *d, *module;
#ifdef WITH_MPI
  PyObject *mpi_module;
#endif
  static void *PyFF_API[PyFF_API_pointers];

  /* Create the module and add the functions */
  m = Py_InitModule("MMTK_pose", pose_methods);
  
  /* Import the array and MPI modules */
#ifdef import_array
  import_array();
#endif
#ifdef WITH_MPI
  import_mpi();
  mpi_module = PyImport_ImportModule("Scientific.MPI");
  if (mpi_module != NULL) {
    PyObject *module_dict = PyModule_GetDict(mpi_module);
    PyExc_MPIError = PyDict_GetItemString(module_dict, "MPIError");
  }
#endif

  /* Add C API pointer array */ 
  PyFF_API[PyFFEnergyTerm_Type_NUM] = (void *)&PyFFEnergyTerm_Type;
  PyFF_API[PyFFEvaluator_Type_NUM] = (void *)&PyFFEvaluator_Type;
  PyFF_API[PyNonbondedList_Type_NUM] = (void *)&PyNonbondedList_Type;
  PyFF_API[PySparseFC_New_NUM] = (void *)&PySparseFC_New;
  PyFF_API[PySparseFC_Type_NUM] = (void *)&PySparseFC_Type;
  PyFF_API[PySparseFC_Zero_NUM] = (void *)&PySparseFC_Zero;
  PyFF_API[PySparseFC_Find_NUM] = (void *)&PySparseFC_Find;
  PyFF_API[PySparseFC_AddTerm_NUM] = (void *)&PySparseFC_AddTerm;
  PyFF_API[PySparseFC_CopyToArray_NUM] = (void *)&PySparseFC_CopyToArray;
  PyFF_API[PySparseFC_AsArray_NUM] = (void *)&PySparseFC_AsArray;
  PyFF_API[PySparseFC_VectorMultiply_NUM] = (void *)&PySparseFC_VectorMultiply;
  PyFF_API[PySparseFC_Scale_NUM] = (void *)&PySparseFC_Scale;
  PyFF_API[PyFFEnergyTerm_New_NUM] = (void *)&PyFFEnergyTerm_New;
  PyFF_API[PyFFEvaluator_New_NUM] = (void *)&PyFFEvaluator_New;
  PyFF_API[PyNonbondedListUpdate_NUM] = (void *)&PyNonbondedListUpdate;
  PyFF_API[PyNonbondedListIterate_NUM] = (void *)&PyNonbondedListIterate;

#ifdef EXTENDED_TYPES
  if (PyType_Ready(&PyFFEnergyTerm_Type) < 0)
    return;
  if (PyType_Ready(&PyFFEvaluator_Type) < 0)
    return;
  if (PyType_Ready(&PyNonbondedList_Type) < 0)
    return;
  if (PyType_Ready(&PySparseFC_Type) < 0)
    return;
#else
  PyFFEnergyTerm_Type.ob_type = &PyType_Type;
  PyFFEvaluator_Type.ob_type = &PyType_Type;
  PyNonbondedList_Type.ob_type = &PyType_Type;
  PySparseFC_Type.ob_type = &PyType_Type;
#endif

  d = PyModule_GetDict(m);
  PyDict_SetItemString(d, "_C_API",
		       PyCObject_FromVoidPtr((void *)PyFF_API, NULL));
  PyDict_SetItemString(d, "EnergyTerm", (PyObject *)&PyFFEnergyTerm_Type);
  PyDict_SetItemString(d, "EnergyEvaluator",
		       (PyObject *)&PyFFEvaluator_Type);

  /* Get the energy conversion factor from Units */
  module = PyImport_ImportModule("MMTK.Units");
  if (module != NULL) {
    PyObject *module_dict = PyModule_GetDict(module);
    PyObject *factor = PyDict_GetItemString(module_dict,
					    "electrostatic_energy");
    electrostatic_energy_factor = PyFloat_AsDouble(factor);
  }

  /* Get function pointers from _universe */
  module = PyImport_ImportModule("MMTK_universe");
  if (module != NULL) {
    PyObject *module_dict = PyModule_GetDict(module);
    PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API");
    PyObject *fn;
    if (PyCObject_Check(c_api_object))
      PyUniverse_API = (void **)PyCObject_AsVoidPtr(c_api_object);
    fn = PyDict_GetItemString(module_dict,
			      "infinite_universe_distance_function");
    distance_vector_pointer = (distance_fn *)PyCObject_AsVoidPtr(fn);
    fn = PyDict_GetItemString(module_dict,
			      "orthorhombic_universe_distance_function");
    orthorhombic_distance_vector_pointer =
                        (distance_fn *)PyCObject_AsVoidPtr(fn);
    fn = PyDict_GetItemString(module_dict,
			      "parallelepipedic_universe_distance_function");
    parallelepipedic_distance_vector_pointer =
                        (distance_fn *)PyCObject_AsVoidPtr(fn);
  }

  /* Check for errors */
  if (PyErr_Occurred())
    Py_FatalError("can't initialize module MMTK_forcefield");
}
static PyObject *
ff_create(PyObject *self, PyObject *args)
{
    PyObject *pypfo, *pycmap, *pyim, *pysite, *pyworker;
    double params[N_PARAMS];
    int eaa=-7, maxiter=-8, nThreads=-9;
    int auto_deepen, periodicity;
    int yflip;
    render_type_t render_type;
    pf_obj *pfo;
    ColorMap *cmap;
    IImage *im;
    IFractalSite *site;
    IFractWorker *worker;

    if(!PyArg_ParseTuple(
	   args,
	   "(ddddddddddd)iiiiOOiiiOOO",
	   &params[0],&params[1],&params[2],&params[3],
	   &params[4],&params[5],&params[6],&params[7],
	   &params[8],&params[9],&params[10],
	   &eaa,&maxiter,&yflip,&nThreads,
	   &pypfo,&pycmap,
	   &auto_deepen,
	   &periodicity,
	   &render_type,
	   &pyim, &pysite,
	   &pyworker
	   ))
    {
	return NULL;
    }

    cmap = (ColorMap *)PyCObject_AsVoidPtr(pycmap);
    pfo = ((pfHandle *)PyCObject_AsVoidPtr(pypfo))->pfo;
    im = (IImage *)PyCObject_AsVoidPtr(pyim);
    site = (IFractalSite *)PyCObject_AsVoidPtr(pysite);
    worker = (IFractWorker *)PyCObject_AsVoidPtr(pyworker);

    if(!cmap || !pfo || !im || !site || !worker)
    {
	return NULL;
    }

    fractFunc *ff = new fractFunc(
	params, 
	eaa,
	maxiter,
	nThreads,
	auto_deepen,
	yflip,
	periodicity,
	render_type,
	-1, // warp_param
	worker,
	im,
	site);

    if(!ff)
    {
	return NULL;
    }

    ffHandle *ffh = new struct ffHandle;
    ffh->ff = ff;
    ffh->pyhandle = pyworker;

    PyObject *pyret = PyCObject_FromVoidPtr(
	ffh,(void (*)(void *))ff_delete);

    Py_INCREF(pyworker);

    return pyret;
}
Beispiel #21
0
/*
 * Add rpm tag dictionaries to the module
 */
static void addRpmTags(PyObject *module)
{
    PyObject * dict = PyDict_New();

#ifdef	NOTYET

    PyObject *pyval, *pyname;
    rpmtd names = rpmtdNew();
    rpmTagGetNames(names, 1);
    const char *tagname, *shortname;
    rpmTag tagval;

    while ((tagname = rpmtdNextString(names))) {
	shortname = tagname + strlen("RPMTAG_");
	tagval = rpmTagGetValue(shortname);

	PyModule_AddIntConstant(module, tagname, tagval);
	pyval = PyInt_FromLong(tagval);
	pyname = PyString_FromString(shortname);
	PyDict_SetItem(dict, pyval, pyname);
	Py_XDECREF(pyval);
	Py_XDECREF(pyname);
    }
    PyModule_AddObject(module, "tagnames", dict);
    rpmtdFreeData(names);
    rpmtdFree(names);

#else

    PyObject * d = PyModule_GetDict(module);
    PyObject * o;

 {  const struct headerTagTableEntry_s * t;
    PyObject * to;
    for (t = rpmTagTable; t && t->name; t++) {
	PyDict_SetItemString(d, (char *) t->name, to=PyInt_FromLong(t->val));
	Py_XDECREF(to);
        PyDict_SetItem(dict, to, o=PyString_FromString(t->name + 7));
	Py_XDECREF(o);
    }
 }

 {  headerSprintfExtension exts = rpmHeaderFormats;
    headerSprintfExtension ext;
    PyObject * to;
    int extNum;
    for (ext = exts, extNum = 0; ext != NULL && ext->type != HEADER_EXT_LAST;
        ext = (ext->type == HEADER_EXT_MORE ? *ext->u.more : ext+1), extNum++)
    {
	if (ext->name == NULL || ext->type != HEADER_EXT_TAG)
	    continue;
	PyDict_SetItemString(d, (char *) ext->name, to=PyCObject_FromVoidPtr((void *)ext, NULL));
	Py_XDECREF(to);
        PyDict_SetItem(dict, to, o=PyString_FromString(ext->name + 7));
	Py_XDECREF(o);
    }
 }

    PyDict_SetItemString(d, "tagnames", dict);
    Py_XDECREF(dict);

#endif
}
static s_param *
parse_params(PyObject *pyarray, int *plen)
{
    struct s_param *params;

    // check and parse fractal params
    if(!PySequence_Check(pyarray))
    {
	PyErr_SetString(PyExc_TypeError,
			"parameters argument should be an array");
	return NULL;
    }


    int len = PySequence_Size(pyarray);
    if(len == 0)
    {
	params = (struct s_param *)malloc(sizeof(struct s_param));
	params[0].t = FLOAT;
	params[0].doubleval = 0.0;
    }
    else if(len > PF_MAXPARAMS)
    {
	PyErr_SetString(PyExc_ValueError,"Too many parameters");
	return NULL;
    }
    else
    {
	int i = 0;
	params = (struct s_param *)malloc(len * sizeof(struct s_param));
	if(!params) return NULL;
	for(i = 0; i < len; ++i)
	{
	    PyObject *pyitem = PySequence_GetItem(pyarray,i);
	    if(NULL == pyitem)
	    {
		return NULL;
	    }
	    if(PyFloat_Check(pyitem))
	    {
		params[i].t = FLOAT;
		params[i].doubleval = PyFloat_AsDouble(pyitem);
		//printf("%d = float(%g)\n",i,params[i].doubleval);
	    }
	    else if(PyInt_Check(pyitem))
	    {
		params[i].t = INT;
		params[i].intval = PyInt_AS_LONG(pyitem);
		//printf("%d = int(%d)\n",i,params[i].intval);
	    }
	    else if(
		PyObject_HasAttrString(pyitem,"cobject") &&
		PyObject_HasAttrString(pyitem,"segments"))
	    {
		PyObject *pycob = PyObject_GetAttrString(pyitem,"cobject");
		if(pycob == Py_None)
		{
		    Py_DECREF(pycob);
		    PyObject *pysegs = PyObject_GetAttrString(
			pyitem,"segments");

		    ColorMap *cmap = cmap_from_pyobject(pysegs);
		    Py_DECREF(pysegs);

		    if(NULL == cmap)
		    {
			return NULL;
		    }

		    pycob = PyCObject_FromVoidPtr(
			cmap, (void (*)(void *))cmap_delete);

		    if(NULL != pycob)
		    {
			PyObject_SetAttrString(pyitem,"cobject",pycob);
			// not quite correct, we are leaking some
			// cmap objects 
			Py_XINCREF(pycob);
		    }
		}
		params[i].t = GRADIENT;
		params[i].gradient = PyCObject_AsVoidPtr(pycob);
		//printf("%d = gradient(%p)\n",i,params[i].gradient);
		Py_DECREF(pycob);
	    }
	    else if(
		PyObject_HasAttrString(pyitem,"_img"))
	    {
		PyObject *pycob = PyObject_GetAttrString(pyitem,"_img");
		params[i].t = PARAM_IMAGE;
		params[i].image = PyCObject_AsVoidPtr(pycob);
		Py_DECREF(pycob);
	    }
	    else
	    {
		Py_XDECREF(pyitem);
		PyErr_SetString(
		    PyExc_ValueError,
		    "All params must be floats, ints, or gradients");
		free(params);
		return NULL;
	    }
	    Py_XDECREF(pyitem);
	} 
    }
    *plen = len;
    return params;
}
Beispiel #23
0
PyObject* create() {
    brisk::BriskDescriptorExtractor* descriptor_extractor = new brisk::BriskDescriptorExtractor();
    return PyCObject_FromVoidPtr(static_cast<void*>(descriptor_extractor), NULL);
}
Beispiel #24
0
static PyObject *mkiir_wrap(PyObject *self, PyObject *args)
{
    double lo, hi, srate;
    double bwfreq, freq, h1, gain;
    PyObject *o;
    FILTER *handle;
    IIRSPEC *filter;

    if (!PyArg_ParseTuple(args, "ddd:mkiir", &lo, &hi, &srate)) {
	return NULL;
    }

    handle = (FILTER *)malloc(sizeof(FILTER));
    handle->type = FILTER_TYPE_IIR;
    filter = &handle->iirspec;
    filter->enable = 1;
    filter->rate = srate;

    if (hi > 0. && lo > 0. && lo < hi) {
	filter->type = BANDPASS;
	filter->order = SIG_ORDER;
	filter->fl = lo;
	filter->fh = hi;
    } else if (hi > 0. && lo > 0. && lo > hi) {
	filter->type = BANDREJECT;
	filter->order = SIG_ORDER;
	filter->fl = hi;
	filter->fh = lo;
    } else if (lo > 0. && hi == 0.) {
	filter->type = HIGHPASS;
	filter->order = 2 * SIG_ORDER;
	filter->fl = lo;
	filter->fh = srate / 2.;
    } else if (lo == 0. && hi > 0.) {
	filter->type = LOWPASS;
	filter->order = 2 * SIG_ORDER;
	filter->fl = 0;
	filter->fh = hi;
    }

    // compute filter coefficients
    if (mkiir(filter) < 0) {
	PyErr_SetString(PyExc_RuntimeError, "mkiir() failed");
	free(handle);
	return NULL;
    }

    // compute effective bandwidth of data filter in steps of 1 milliHz
    for (freq = bwfreq = 0.; freq < srate / 4.; freq += 0.001) {
	h1 = response(filter, srate, freq);
	if (h1 > M_SQRT2) {
	    PyErr_SetString(PyExc_RuntimeError, "mkiir() failed: IIR filter is unstable for this sample rate");
	    free(handle);
	    return NULL;
	}
	bwfreq += 0.001 * (h1 * h1);
    }

    // test filter for low gain
    gain = bwfreq / (hi - lo);
    if (gain < M_SQRT1_2) {
	printf("nominal filter bandwidth=%f\n", bwfreq);
	PyErr_SetString(PyExc_RuntimeError, "WARNING: IIR filter gain too low");
	free(handle);
	return NULL;
    }

    o = PyCObject_FromVoidPtr(handle, free_filter);
    return o;
}
Beispiel #25
0
init_cairo(void)
{
    PyObject *m;

    /* initialise 'tp_base' here to work round problem with MinGW compiler */
    PycairoContext_Type.tp_base = &PyBaseObject_Type;
    if (PyType_Ready(&PycairoContext_Type) < 0)
        return;
    PycairoFontFace_Type.tp_base = &PyBaseObject_Type;
    if (PyType_Ready(&PycairoFontFace_Type) < 0)
        return;
    PycairoToyFontFace_Type.tp_base = &PycairoFontFace_Type;
    if (PyType_Ready(&PycairoToyFontFace_Type) < 0)
        return;
    PycairoFontOptions_Type.tp_base = &PyBaseObject_Type;
    if (PyType_Ready(&PycairoFontOptions_Type) < 0)
        return;
    PycairoMatrix_Type.tp_base = &PyBaseObject_Type;
    if (PyType_Ready(&PycairoMatrix_Type) < 0)
        return;
    PycairoPath_Type.tp_base = &PyBaseObject_Type;
    if (PyType_Ready(&PycairoPath_Type) < 0)
	return;
    PycairoPathiter_Type.tp_iter=&PyObject_SelfIter;

    PycairoPattern_Type.tp_base = &PyBaseObject_Type;
    if (PyType_Ready(&PycairoPattern_Type) < 0)
        return;
    PycairoSolidPattern_Type.tp_base = &PycairoPattern_Type;
    if (PyType_Ready(&PycairoSolidPattern_Type) < 0)
        return;
    PycairoSurfacePattern_Type.tp_base = &PycairoPattern_Type;
    if (PyType_Ready(&PycairoSurfacePattern_Type) < 0)
        return;
    PycairoGradient_Type.tp_base = &PycairoPattern_Type;
    if (PyType_Ready(&PycairoGradient_Type) < 0)
        return;
    PycairoLinearGradient_Type.tp_base = &PycairoGradient_Type;
    if (PyType_Ready(&PycairoLinearGradient_Type) < 0)
        return;
    PycairoRadialGradient_Type.tp_base = &PycairoGradient_Type;
    if (PyType_Ready(&PycairoRadialGradient_Type) < 0)
        return;

    PycairoScaledFont_Type.tp_base = &PyBaseObject_Type;
    if (PyType_Ready(&PycairoScaledFont_Type) < 0)
        return;

    PycairoSurface_Type.tp_base = &PyBaseObject_Type;
    if (PyType_Ready(&PycairoSurface_Type) < 0)
        return;
#ifdef CAIRO_HAS_IMAGE_SURFACE
    PycairoImageSurface_Type.tp_base = &PycairoSurface_Type;
    if (PyType_Ready(&PycairoImageSurface_Type) < 0)
        return;
#endif
#ifdef CAIRO_HAS_PDF_SURFACE
    PycairoPDFSurface_Type.tp_base = &PycairoSurface_Type;
    if (PyType_Ready(&PycairoPDFSurface_Type) < 0)
        return;
#endif
#ifdef CAIRO_HAS_PS_SURFACE
    PycairoPSSurface_Type.tp_base = &PycairoSurface_Type;
    if (PyType_Ready(&PycairoPSSurface_Type) < 0)
        return;
#endif
#ifdef CAIRO_HAS_SVG_SURFACE
    PycairoSVGSurface_Type.tp_base = &PycairoSurface_Type;
    if (PyType_Ready(&PycairoSVGSurface_Type) < 0)
        return;
#endif
#ifdef CAIRO_HAS_WIN32_SURFACE
    PycairoWin32Surface_Type.tp_base = &PycairoSurface_Type;
    if (PyType_Ready(&PycairoWin32Surface_Type) < 0)
        return;
#endif
#ifdef CAIRO_HAS_XLIB_SURFACE
    PycairoXlibSurface_Type.tp_base = &PycairoSurface_Type;
    if (PyType_Ready(&PycairoXlibSurface_Type) < 0)
        return;
#endif

    m = Py_InitModule("cairo._cairo", cairo_functions);

    PyModule_AddStringConstant(m, "version", pycairo_version_string);
    PyModule_AddObject(m, "version_info",
		       Py_BuildValue("(iii)", VERSION_MAJOR, VERSION_MINOR,
				     VERSION_MICRO));

    Py_INCREF(&PycairoContext_Type);
    PyModule_AddObject(m, "Context", (PyObject *)&PycairoContext_Type);
    Py_INCREF(&PycairoFontFace_Type);
    PyModule_AddObject(m, "FontFace",(PyObject *)&PycairoFontFace_Type);
    Py_INCREF(&PycairoToyFontFace_Type);
    PyModule_AddObject(m, "ToyFontFace",(PyObject *)&PycairoToyFontFace_Type);
    Py_INCREF(&PycairoFontOptions_Type);
    PyModule_AddObject(m, "FontOptions",(PyObject *)&PycairoFontOptions_Type);
    Py_INCREF(&PycairoMatrix_Type);
    PyModule_AddObject(m, "Matrix",  (PyObject *)&PycairoMatrix_Type);
    Py_INCREF(&PycairoPath_Type);
    /* Don't add Path object since it is not accessed directly as 'cairo.Path'
     * PyModule_AddObject(m, "Path", (PyObject *)&PycairoPath_Type);
     */
    Py_INCREF(&PycairoPattern_Type);
    PyModule_AddObject(m, "Pattern", (PyObject *)&PycairoPattern_Type);
    Py_INCREF(&PycairoSolidPattern_Type);
    PyModule_AddObject(m, "SolidPattern",
		       (PyObject *)&PycairoSolidPattern_Type);
    Py_INCREF(&PycairoSurfacePattern_Type);
    PyModule_AddObject(m, "SurfacePattern",
		       (PyObject *)&PycairoSurfacePattern_Type);
    Py_INCREF(&PycairoGradient_Type);
    PyModule_AddObject(m, "Gradient", (PyObject *)&PycairoGradient_Type);
    Py_INCREF(&PycairoLinearGradient_Type);
    PyModule_AddObject(m, "LinearGradient",
		       (PyObject *)&PycairoLinearGradient_Type);
    Py_INCREF(&PycairoRadialGradient_Type);
    PyModule_AddObject(m, "RadialGradient",
		       (PyObject *)&PycairoRadialGradient_Type);

    Py_INCREF(&PycairoScaledFont_Type);
    PyModule_AddObject(m, "ScaledFont", (PyObject *)&PycairoScaledFont_Type);

    Py_INCREF(&PycairoSurface_Type);
    PyModule_AddObject(m, "Surface", (PyObject *)&PycairoSurface_Type);

#ifdef CAIRO_HAS_IMAGE_SURFACE
    Py_INCREF(&PycairoImageSurface_Type);
    PyModule_AddObject(m, "ImageSurface",
		       (PyObject *)&PycairoImageSurface_Type);
#endif

#ifdef CAIRO_HAS_PDF_SURFACE
    Py_INCREF(&PycairoPDFSurface_Type);
    PyModule_AddObject(m, "PDFSurface", (PyObject *)&PycairoPDFSurface_Type);
#endif

#ifdef CAIRO_HAS_PS_SURFACE
    Py_INCREF(&PycairoPSSurface_Type);
    PyModule_AddObject(m, "PSSurface", (PyObject *)&PycairoPSSurface_Type);
#endif

#ifdef CAIRO_HAS_SVG_SURFACE
    Py_INCREF(&PycairoSVGSurface_Type);
    PyModule_AddObject(m, "SVGSurface", (PyObject *)&PycairoSVGSurface_Type);
#endif

#ifdef CAIRO_HAS_WIN32_SURFACE
    Py_INCREF(&PycairoWin32Surface_Type);
    PyModule_AddObject(m, "Win32Surface",
		       (PyObject *)&PycairoWin32Surface_Type);
#endif

#ifdef CAIRO_HAS_XLIB_SURFACE
    Py_INCREF(&PycairoXlibSurface_Type);
    PyModule_AddObject(m, "XlibSurface",
		       (PyObject *)&PycairoXlibSurface_Type);
#endif

    PyModule_AddObject(m, "CAPI", PyCObject_FromVoidPtr(&CAPI, NULL));

    /* Add 'cairo.Error' to the module */
    if (CairoError == NULL) {
	CairoError = PyErr_NewException("cairo.Error", NULL, NULL);
	if (CairoError == NULL)
	    return;
    }
    Py_INCREF(CairoError);
    if (PyModule_AddObject(m, "Error", CairoError) < 0)
	return;

    /* constants */
#if CAIRO_HAS_ATSUI_FONT
    PyModule_AddIntConstant(m, "HAS_ATSUI_FONT", 1);
#else
    PyModule_AddIntConstant(m, "HAS_ATSUI_FONT", 0);
#endif
#if CAIRO_HAS_FT_FONT
    PyModule_AddIntConstant(m, "HAS_FT_FONT", 1);
#else
    PyModule_AddIntConstant(m, "HAS_FT_FONT", 0);
#endif
#if CAIRO_HAS_GLITZ_SURFACE
    PyModule_AddIntConstant(m, "HAS_GLITZ_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_GLITZ_SURFACE", 0);
#endif
#if CAIRO_HAS_IMAGE_SURFACE
    PyModule_AddIntConstant(m, "HAS_IMAGE_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_IMAGE_SURFACE", 0);
#endif
#if CAIRO_HAS_PDF_SURFACE
    PyModule_AddIntConstant(m, "HAS_PDF_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_PDF_SURFACE", 0);
#endif
#if CAIRO_HAS_PNG_FUNCTIONS
    PyModule_AddIntConstant(m, "HAS_PNG_FUNCTIONS", 1);
#else
    PyModule_AddIntConstant(m, "HAS_PNG_FUNCTIONS", 0);
#endif
#if CAIRO_HAS_PS_SURFACE
    PyModule_AddIntConstant(m, "HAS_PS_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_PS_SURFACE", 0);
#endif
#if CAIRO_HAS_SVG_SURFACE
    PyModule_AddIntConstant(m, "HAS_SVG_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_SVG_SURFACE", 0);
#endif
#if CAIRO_HAS_USER_FONT
    PyModule_AddIntConstant(m, "HAS_USER_FONT", 1);
#else
    PyModule_AddIntConstant(m, "HAS_USER_FONT", 0);
#endif
#if CAIRO_HAS_QUARTZ_SURFACE
    PyModule_AddIntConstant(m, "HAS_QUARTZ_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_QUARTZ_SURFACE", 0);
#endif
#if CAIRO_HAS_WIN32_FONT
    PyModule_AddIntConstant(m, "HAS_WIN32_FONT", 1);
#else
    PyModule_AddIntConstant(m, "HAS_WIN32_FONT", 0);
#endif
#if CAIRO_HAS_WIN32_SURFACE
    PyModule_AddIntConstant(m, "HAS_WIN32_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_WIN32_SURFACE", 0);
#endif
#if CAIRO_HAS_XCB_SURFACE
    PyModule_AddIntConstant(m, "HAS_XCB_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_XCB_SURFACE", 0);
#endif
#if CAIRO_HAS_XLIB_SURFACE
    PyModule_AddIntConstant(m, "HAS_XLIB_SURFACE", 1);
#else
    PyModule_AddIntConstant(m, "HAS_XLIB_SURFACE", 0);
#endif

#define CONSTANT(x) PyModule_AddIntConstant(m, #x, CAIRO_##x)
    CONSTANT(ANTIALIAS_DEFAULT);
    CONSTANT(ANTIALIAS_NONE);
    CONSTANT(ANTIALIAS_GRAY);
    CONSTANT(ANTIALIAS_SUBPIXEL);

    CONSTANT(CONTENT_COLOR);
    CONSTANT(CONTENT_ALPHA);
    CONSTANT(CONTENT_COLOR_ALPHA);

    CONSTANT(EXTEND_NONE);
    CONSTANT(EXTEND_REPEAT);
    CONSTANT(EXTEND_REFLECT);
    CONSTANT(EXTEND_PAD);

    CONSTANT(FILL_RULE_WINDING);
    CONSTANT(FILL_RULE_EVEN_ODD);

    CONSTANT(FILTER_FAST);
    CONSTANT(FILTER_GOOD);
    CONSTANT(FILTER_BEST);
    CONSTANT(FILTER_NEAREST);
    CONSTANT(FILTER_BILINEAR);
    CONSTANT(FILTER_GAUSSIAN);

    CONSTANT(FONT_WEIGHT_NORMAL);
    CONSTANT(FONT_WEIGHT_BOLD);

    CONSTANT(FONT_SLANT_NORMAL);
    CONSTANT(FONT_SLANT_ITALIC);
    CONSTANT(FONT_SLANT_OBLIQUE);

    CONSTANT(FORMAT_ARGB32);
    CONSTANT(FORMAT_RGB24);
    CONSTANT(FORMAT_A8);
    CONSTANT(FORMAT_A1);

    CONSTANT(HINT_METRICS_DEFAULT);
    CONSTANT(HINT_METRICS_OFF);
    CONSTANT(HINT_METRICS_ON);

    CONSTANT(HINT_STYLE_DEFAULT);
    CONSTANT(HINT_STYLE_NONE);
    CONSTANT(HINT_STYLE_SLIGHT);
    CONSTANT(HINT_STYLE_MEDIUM);
    CONSTANT(HINT_STYLE_FULL);

    CONSTANT(LINE_CAP_BUTT);
    CONSTANT(LINE_CAP_ROUND);
    CONSTANT(LINE_CAP_SQUARE);

    CONSTANT(LINE_JOIN_MITER);
    CONSTANT(LINE_JOIN_ROUND);
    CONSTANT(LINE_JOIN_BEVEL);

    CONSTANT(OPERATOR_CLEAR);

    CONSTANT(OPERATOR_SOURCE);
    CONSTANT(OPERATOR_OVER);
    CONSTANT(OPERATOR_IN);
    CONSTANT(OPERATOR_OUT);
    CONSTANT(OPERATOR_ATOP);

    CONSTANT(OPERATOR_DEST);
    CONSTANT(OPERATOR_DEST_OVER);
    CONSTANT(OPERATOR_DEST_IN);
    CONSTANT(OPERATOR_DEST_OUT);
    CONSTANT(OPERATOR_DEST_ATOP);

    CONSTANT(OPERATOR_XOR);
    CONSTANT(OPERATOR_ADD);
    CONSTANT(OPERATOR_SATURATE);

    CONSTANT(PATH_MOVE_TO);
    CONSTANT(PATH_LINE_TO);
    CONSTANT(PATH_CURVE_TO);
    CONSTANT(PATH_CLOSE_PATH);

#ifdef CAIRO_HAS_PS_SURFACE
    CONSTANT(PS_LEVEL_2);
    CONSTANT(PS_LEVEL_3);
#endif

    CONSTANT(SUBPIXEL_ORDER_DEFAULT);
    CONSTANT(SUBPIXEL_ORDER_RGB);
    CONSTANT(SUBPIXEL_ORDER_BGR);
    CONSTANT(SUBPIXEL_ORDER_VRGB);
    CONSTANT(SUBPIXEL_ORDER_VBGR);
#undef CONSTANT
}
Beispiel #26
0
/*
 * Initialize SSL sub module
 *
 * Arguments: None
 * Returns:   None
 */
void
initSSL(void)
{
    static void *ssl_API[ssl_API_pointers];
    PyObject *ssl_api_object;
    PyObject *module;

    SSL_library_init();
    ERR_load_SSL_strings();

    import_crypto();

    if ((module = Py_InitModule3("SSL", ssl_methods, ssl_doc)) == NULL) {
        return;
    }

    /* Initialize the C API pointer array */
    ssl_API[ssl_Context_New_NUM]    = (void *)ssl_Context_New;
    ssl_API[ssl_Connection_New_NUM] = (void *)ssl_Connection_New;
    ssl_api_object = PyCObject_FromVoidPtr((void *)ssl_API, NULL);
    if (ssl_api_object != NULL)
        PyModule_AddObject(module, "_C_API", ssl_api_object);

    /* Exceptions */
/*
 * ADD_EXCEPTION(dict,name,base) expands to a correct Exception declaration,
 * inserting OpenSSL.SSL.name into dict, derviving the exception from base.
 */
#define ADD_EXCEPTION(_name, _base)                                    \
do {                                                                          \
    ssl_##_name = PyErr_NewException("OpenSSL.SSL."#_name, _base, NULL);\
    if (ssl_##_name == NULL)                                            \
        goto error;                                                           \
    if (PyModule_AddObject(module, #_name, ssl_##_name) != 0)           \
        goto error;                                                           \
} while (0)

    ssl_Error = PyErr_NewException("OpenSSL.SSL.Error", NULL, NULL);
    if (ssl_Error == NULL)
        goto error;
    if (PyModule_AddObject(module, "Error", ssl_Error) != 0)
        goto error;

    ADD_EXCEPTION(ZeroReturnError,     ssl_Error);
    ADD_EXCEPTION(WantReadError,       ssl_Error);
    ADD_EXCEPTION(WantWriteError,      ssl_Error);
    ADD_EXCEPTION(WantX509LookupError, ssl_Error);
    ADD_EXCEPTION(SysCallError,        ssl_Error);
#undef ADD_EXCEPTION

    /* Method constants */
    PyModule_AddIntConstant(module, "SSLv2_METHOD",  ssl_SSLv2_METHOD);
    PyModule_AddIntConstant(module, "SSLv3_METHOD",  ssl_SSLv3_METHOD);
    PyModule_AddIntConstant(module, "SSLv23_METHOD", ssl_SSLv23_METHOD);
    PyModule_AddIntConstant(module, "TLSv1_METHOD",  ssl_TLSv1_METHOD);

    /* Verify constants */
    PyModule_AddIntConstant(module, "VERIFY_NONE", SSL_VERIFY_NONE);
    PyModule_AddIntConstant(module, "VERIFY_PEER", SSL_VERIFY_PEER);
    PyModule_AddIntConstant(module, "VERIFY_FAIL_IF_NO_PEER_CERT",
                            SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
    PyModule_AddIntConstant(module, "VERIFY_CLIENT_ONCE",
                            SSL_VERIFY_CLIENT_ONCE);

    /* File type constants */
    PyModule_AddIntConstant(module, "FILETYPE_PEM",  SSL_FILETYPE_PEM);
    PyModule_AddIntConstant(module, "FILETYPE_ASN1", SSL_FILETYPE_ASN1);

    /* SSL option constants */
    PyModule_AddIntConstant(module, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
    PyModule_AddIntConstant(module, "OP_EPHEMERAL_RSA", SSL_OP_EPHEMERAL_RSA);
    PyModule_AddIntConstant(module, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
    PyModule_AddIntConstant(module, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
    PyModule_AddIntConstant(module, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);

    /* More SSL option constants */
    PyModule_AddIntConstant(module, "OP_MICROSOFT_SESS_ID_BUG", SSL_OP_MICROSOFT_SESS_ID_BUG);
    PyModule_AddIntConstant(module, "OP_NETSCAPE_CHALLENGE_BUG", SSL_OP_NETSCAPE_CHALLENGE_BUG);
    PyModule_AddIntConstant(module, "OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG);
    PyModule_AddIntConstant(module, "OP_SSLREF2_REUSE_CERT_TYPE_BUG", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG);
    PyModule_AddIntConstant(module, "OP_MICROSOFT_BIG_SSLV3_BUFFER", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER);
    PyModule_AddIntConstant(module, "OP_MSIE_SSLV2_RSA_PADDING", SSL_OP_MSIE_SSLV2_RSA_PADDING);
    PyModule_AddIntConstant(module, "OP_SSLEAY_080_CLIENT_DH_BUG", SSL_OP_SSLEAY_080_CLIENT_DH_BUG);
    PyModule_AddIntConstant(module, "OP_TLS_D5_BUG", SSL_OP_TLS_D5_BUG);
    PyModule_AddIntConstant(module, "OP_TLS_BLOCK_PADDING_BUG", SSL_OP_TLS_BLOCK_PADDING_BUG);
    PyModule_AddIntConstant(module, "OP_DONT_INSERT_EMPTY_FRAGMENTS", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
    PyModule_AddIntConstant(module, "OP_ALL", SSL_OP_ALL);
    PyModule_AddIntConstant(module, "OP_CIPHER_SERVER_PREFERENCE", SSL_OP_CIPHER_SERVER_PREFERENCE);
    PyModule_AddIntConstant(module, "OP_TLS_ROLLBACK_BUG", SSL_OP_TLS_ROLLBACK_BUG);
    PyModule_AddIntConstant(module, "OP_PKCS1_CHECK_1", SSL_OP_PKCS1_CHECK_1);
    PyModule_AddIntConstant(module, "OP_PKCS1_CHECK_2", SSL_OP_PKCS1_CHECK_2);
    PyModule_AddIntConstant(module, "OP_NETSCAPE_CA_DN_BUG", SSL_OP_NETSCAPE_CA_DN_BUG);
    PyModule_AddIntConstant(module, "OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);

    /* DTLS related options.  The first two of these were introduced in
     * 2005, the third in 2007.  To accomodate systems which are still using
     * older versions, make them optional. */
#ifdef SSL_OP_NO_QUERY_MTU
    PyModule_AddIntConstant(module, "OP_NO_QUERY_MTU", SSL_OP_NO_QUERY_MTU);
#endif
#ifdef SSL_OP_COOKIE_EXCHANGE
    PyModule_AddIntConstant(module, "OP_COOKIE_EXCHANGE", SSL_OP_COOKIE_EXCHANGE);
#endif
#ifdef SSL_OP_NO_TICKET
    PyModule_AddIntConstant(module, "OP_NO_TICKET", SSL_OP_NO_TICKET);
#endif

    /* For SSL_set_shutdown */
    PyModule_AddIntConstant(module, "SENT_SHUTDOWN", SSL_SENT_SHUTDOWN);
    PyModule_AddIntConstant(module, "RECEIVED_SHUTDOWN", SSL_RECEIVED_SHUTDOWN);

    if (!init_ssl_context(module))
        goto error;
    if (!init_ssl_connection(module))
        goto error;

#ifdef WITH_THREAD
    /*
     * Initialize this module's threading support structures.
     */
    _pyOpenSSL_tstate_key = PyThread_create_key();
#endif

  error:
    ;
}
PyMODINIT_FUNC
INIT_MODULE(_psycopg)(void)
{
#if PY_VERSION_HEX < 0x03020000
    static void *PSYCOPG_API[PSYCOPG_API_pointers];
    PyObject *c_api_object;
#endif

    PyObject *module = NULL, *dict;

#ifdef PSYCOPG_DEBUG
    if (getenv("PSYCOPG_DEBUG"))
        psycopg_debug_enabled = 1;
#endif

    Dprintf("initpsycopg: initializing psycopg %s", PSYCOPG_VERSION);

    /* initialize all the new types and then the module */
    Py_TYPE(&connectionType) = &PyType_Type;
    if (PyType_Ready(&connectionType) == -1) goto exit;

    Py_TYPE(&cursorType) = &PyType_Type;
    if (PyType_Ready(&cursorType) == -1) goto exit;

    Py_TYPE(&typecastType) = &PyType_Type;
    if (PyType_Ready(&typecastType) == -1) goto exit;

    Py_TYPE(&qstringType) = &PyType_Type;
    if (PyType_Ready(&qstringType) == -1) goto exit;

    Py_TYPE(&binaryType) = &PyType_Type;
    if (PyType_Ready(&binaryType) == -1) goto exit;

    Py_TYPE(&isqlquoteType) = &PyType_Type;
    if (PyType_Ready(&isqlquoteType) == -1) goto exit;

    Py_TYPE(&pbooleanType) = &PyType_Type;
    if (PyType_Ready(&pbooleanType) == -1) goto exit;

    Py_TYPE(&pintType) = &PyType_Type;
    if (PyType_Ready(&pintType) == -1) goto exit;

    Py_TYPE(&pfloatType) = &PyType_Type;
    if (PyType_Ready(&pfloatType) == -1) goto exit;

    Py_TYPE(&pdecimalType) = &PyType_Type;
    if (PyType_Ready(&pdecimalType) == -1) goto exit;

    Py_TYPE(&asisType) = &PyType_Type;
    if (PyType_Ready(&asisType) == -1) goto exit;

    Py_TYPE(&listType) = &PyType_Type;
    if (PyType_Ready(&listType) == -1) goto exit;

    Py_TYPE(&chunkType) = &PyType_Type;
    if (PyType_Ready(&chunkType) == -1) goto exit;

    Py_TYPE(&notifyType) = &PyType_Type;
    if (PyType_Ready(&notifyType) == -1) goto exit;

    Py_TYPE(&xidType) = &PyType_Type;
    if (PyType_Ready(&xidType) == -1) goto exit;

    Py_TYPE(&errorType) = &PyType_Type;
    errorType.tp_base = (PyTypeObject *)PyExc_StandardError;
    if (PyType_Ready(&errorType) == -1) goto exit;

    Py_TYPE(&diagnosticsType) = &PyType_Type;
    if (PyType_Ready(&diagnosticsType) == -1) goto exit;

    Py_TYPE(&lobjectType) = &PyType_Type;
    if (PyType_Ready(&lobjectType) == -1) goto exit;

    /* initialize libcrypto threading callbacks */
    psyco_libcrypto_threads_init();

    /* import mx.DateTime module, if necessary */
#ifdef HAVE_MXDATETIME
    Py_TYPE(&mxdatetimeType) = &PyType_Type;
    if (PyType_Ready(&mxdatetimeType) == -1) goto exit;

    if (0 != mxDateTime_ImportModuleAndAPI()) {
        PyErr_Clear();

        /* only fail if the mx typacaster should have been the default */
#ifdef PSYCOPG_DEFAULT_MXDATETIME
        PyErr_SetString(PyExc_ImportError,
            "can't import mx.DateTime module (requested as default adapter)");
        goto exit;
#endif
    }
#endif

    /* import python builtin datetime module, if available */
    pyDateTimeModuleP = PyImport_ImportModule("datetime");
    if (pyDateTimeModuleP == NULL) {
        Dprintf("initpsycopg: can't import datetime module");
        PyErr_SetString(PyExc_ImportError, "can't import datetime module");
        goto exit;
    }

    /* Initialize the PyDateTimeAPI everywhere is used */
    PyDateTime_IMPORT;
    if (psyco_adapter_datetime_init()) { goto exit; }

    Py_TYPE(&pydatetimeType) = &PyType_Type;
    if (PyType_Ready(&pydatetimeType) == -1) goto exit;

    /* initialize the module and grab module's dictionary */
#if PY_MAJOR_VERSION < 3
    module = Py_InitModule("_psycopg", psycopgMethods);
#else
    module = PyModule_Create(&psycopgmodule);
#endif
    if (!module) { goto exit; }

    dict = PyModule_GetDict(module);

    /* initialize all the module's exported functions */
    /* PyBoxer_API[PyBoxer_Fake_NUM] = (void *)PyBoxer_Fake; */

    /* Create a CObject containing the API pointer array's address */
    /* If anybody asks for a PyCapsule we'll deal with it. */
#if PY_VERSION_HEX < 0x03020000
    c_api_object = PyCObject_FromVoidPtr((void *)PSYCOPG_API, NULL);
    if (c_api_object != NULL)
        PyModule_AddObject(module, "_C_API", c_api_object);
#endif

    /* other mixed initializations of module-level variables */
    if (!(psycoEncodings = PyDict_New())) { goto exit; }
    if (0 != psyco_encodings_fill(psycoEncodings)) { goto exit; }
    psyco_null = Bytes_FromString("NULL");
    if (!(psyco_DescriptionType = psyco_make_description_type())) { goto exit; }

    /* set some module's parameters */
    PyModule_AddStringConstant(module, "__version__", PSYCOPG_VERSION);
    PyModule_AddStringConstant(module, "__doc__", "psycopg PostgreSQL driver");
    PyModule_AddIntConstant(module, "__libpq_version__", PG_VERSION_NUM);
    PyModule_AddObject(module, "apilevel", Text_FromUTF8(APILEVEL));
    PyModule_AddObject(module, "threadsafety", PyInt_FromLong(THREADSAFETY));
    PyModule_AddObject(module, "paramstyle", Text_FromUTF8(PARAMSTYLE));

    /* put new types in module dictionary */
    PyModule_AddObject(module, "connection", (PyObject*)&connectionType);
    PyModule_AddObject(module, "cursor", (PyObject*)&cursorType);
    PyModule_AddObject(module, "ISQLQuote", (PyObject*)&isqlquoteType);
    PyModule_AddObject(module, "Notify", (PyObject*)&notifyType);
    PyModule_AddObject(module, "Xid", (PyObject*)&xidType);
    PyModule_AddObject(module, "Diagnostics", (PyObject*)&diagnosticsType);
    PyModule_AddObject(module, "AsIs", (PyObject*)&asisType);
    PyModule_AddObject(module, "Binary", (PyObject*)&binaryType);
    PyModule_AddObject(module, "Boolean", (PyObject*)&pbooleanType);
    PyModule_AddObject(module, "Decimal", (PyObject*)&pdecimalType);
    PyModule_AddObject(module, "Int", (PyObject*)&pintType);
    PyModule_AddObject(module, "Float", (PyObject*)&pfloatType);
    PyModule_AddObject(module, "List", (PyObject*)&listType);
    PyModule_AddObject(module, "QuotedString", (PyObject*)&qstringType);
    PyModule_AddObject(module, "lobject", (PyObject*)&lobjectType);
    PyModule_AddObject(module, "Column", psyco_DescriptionType);

    /* encodings dictionary in module dictionary */
    PyModule_AddObject(module, "encodings", psycoEncodings);

#ifdef HAVE_MXDATETIME
    /* If we can't find mx.DateTime objects at runtime,
     * remove them from the module (and, as consequence, from the adapters). */
    if (0 != psyco_adapter_mxdatetime_init()) {
        PyDict_DelItemString(dict, "DateFromMx");
        PyDict_DelItemString(dict, "TimeFromMx");
        PyDict_DelItemString(dict, "TimestampFromMx");
        PyDict_DelItemString(dict, "IntervalFromMx");
    }
#endif
    /* initialize default set of typecasters */
    if (0 != typecast_init(dict)) { goto exit; }

    /* initialize microprotocols layer */
    microprotocols_init(dict);
    if (0 != psyco_adapters_init(dict)) { goto exit; }

    /* create a standard set of exceptions and add them to the module's dict */
    if (0 != psyco_errors_init()) { goto exit; }
    psyco_errors_fill(dict);

    Dprintf("initpsycopg: module initialization complete");

exit:
#if PY_MAJOR_VERSION > 2
    return module;
#else
    return;
#endif
}
Beispiel #28
0
static GnmFuncHelp const *
python_function_get_gnumeric_help (PyObject *python_fn_info_dict, PyObject *python_fn,
                                   const gchar *fn_name)
{
	gchar *help_attr_name;
	PyObject *cobject_help_value;
	PyObject *python_arg_names;
	PyObject *fn_info_obj;

	fn_info_obj = PyDict_GetItemString (python_fn_info_dict, (gchar *) fn_name);
	python_arg_names = PyTuple_GetItem (fn_info_obj, 1);

	help_attr_name = g_strdup_printf ("_CGnumericHelp_%s", fn_name);
	cobject_help_value = PyDict_GetItemString (python_fn_info_dict, help_attr_name);
	if (cobject_help_value == NULL) {
		PyObject *python_fn_help =
			PyFunction_Check (python_fn)
			? ((PyFunctionObject *) python_fn)->func_doc
			: NULL;
		if (python_fn_help != NULL && PyString_Check (python_fn_help)) {
			guint n = 0;
			GnmFuncHelp *new_help = NULL;
			gboolean arg_names_written = FALSE;
			char const *help_text = PyString_AsString (python_fn_help);

			if (g_str_has_prefix (help_text, "@GNM_FUNC_HELP_NAME@")) {
				/* New-style documentation */
				gchar **items = g_strsplit (help_text, "\n", 0), **fitems = items;
				while (*items) {
					if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_NAME@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_NAME;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_NAME@"));
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_ARG@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_ARG;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_ARG@"));
						arg_names_written = TRUE;
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_DESCRIPTION@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_DESCRIPTION;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_DESCRIPTION@"));
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_EXAMPLES@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_EXAMPLES;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_EXAMPLES@"));
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_SEEALSO@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_SEEALSO;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_SEEALSO@"));
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_EXTREF@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_EXTREF;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_EXTREF@"));
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_NOTE@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_NOTE;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_NOTE@"));
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_END@")) {
						/* ignore */
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_EXCEL@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_EXCEL;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_EXCEL@"));
					} else if (g_str_has_prefix (*items, "@GNM_FUNC_HELP_ODF@")) {
						guint it = n;
						new_help = g_renew (GnmFuncHelp, new_help, ++n);
						new_help[it].type = GNM_FUNC_HELP_ODF;
						new_help[it].text = g_strdup ((*items) + strlen ("@GNM_FUNC_HELP_ODF@"));
					} else if (n > 0) {
						gchar *old_text = (gchar *) new_help[n].text;
						new_help[n].text = g_strconcat (old_text, "\n", *items, NULL);
						g_free (old_text);
					}
					items++;
				}
				g_strfreev (fitems);
			}

			if (python_arg_names != NULL && !arg_names_written) {
				/* We only try this if we did not get argument  */
				/* descriptions via the new style documentation */
				char const *arg_names = PyString_AsString (python_arg_names);
				if (arg_names != NULL && arg_names[0] != '\0') {
					gchar **args = g_strsplit (arg_names, ",", 0);
					guint nitems = g_strv_length (args), nstart = n, i;
					n += nitems;
					new_help = g_renew (GnmFuncHelp, new_help, n);
					for (i = 0; i < nitems; i++, nstart++) {
						char const *arg_name = args[i];
						while (*arg_name == ' ') arg_name++;
						new_help[nstart].type = GNM_FUNC_HELP_ARG;
						new_help[nstart].text = g_strdup_printf ("%s:", arg_name);
					}
					g_strfreev (args);
				}
			}

			n++;
			new_help = g_renew (GnmFuncHelp, new_help, n);
			new_help[n-1].type = GNM_FUNC_HELP_END;
			new_help[n-1].text = NULL;

			cobject_help_value = PyCObject_FromVoidPtr (new_help, &g_free);
			PyDict_SetItemString (python_fn_info_dict, help_attr_name, cobject_help_value);
		}
	}
	g_free (help_attr_name);
	if (cobject_help_value == NULL)
		return NULL;

	return (GnmFuncHelp const *) PyCObject_AsVoidPtr (cobject_help_value);
}
Beispiel #29
0
PyMODINIT_FUNC
initgreenlet(void)
#endif
{
	PyObject* m = NULL;
	char** p = NULL;
	PyObject *c_api_object;
	static void *_PyGreenlet_API[PyGreenlet_API_pointers];

	GREENLET_NOINLINE_INIT();

#if PY_MAJOR_VERSION >= 3
	m = PyModule_Create(&greenlet_module_def);
#else
	m = Py_InitModule("greenlet", GreenMethods);
#endif
	if (m == NULL)
	{
		INITERROR;
	}

	if (PyModule_AddStringConstant(m, "__version__", GREENLET_VERSION) < 0)
	{
		INITERROR;
	}

#if PY_MAJOR_VERSION >= 3
	ts_curkey = PyUnicode_InternFromString("__greenlet_ts_curkey");
	ts_delkey = PyUnicode_InternFromString("__greenlet_ts_delkey");
#else
	ts_curkey = PyString_InternFromString("__greenlet_ts_curkey");
	ts_delkey = PyString_InternFromString("__greenlet_ts_delkey");
#endif
	if (ts_curkey == NULL || ts_delkey == NULL)
	{
		INITERROR;
	}
	if (PyType_Ready(&PyGreenlet_Type) < 0)
	{
		INITERROR;
	}
	PyExc_GreenletError = PyErr_NewException("greenlet.error", NULL, NULL);
	if (PyExc_GreenletError == NULL)
	{
		INITERROR;
	}
#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
	PyExc_GreenletExit = PyErr_NewException("greenlet.GreenletExit",
						PyExc_BaseException, NULL);
#else
	PyExc_GreenletExit = PyErr_NewException("greenlet.GreenletExit",
						NULL, NULL);
#endif
	if (PyExc_GreenletExit == NULL)
	{
		INITERROR;
	}

	ts_current = green_create_main();
	if (ts_current == NULL)
	{
		INITERROR;
	}

	Py_INCREF(&PyGreenlet_Type);
	PyModule_AddObject(m, "greenlet", (PyObject*) &PyGreenlet_Type);
	Py_INCREF(PyExc_GreenletError);
	PyModule_AddObject(m, "error", PyExc_GreenletError);
	Py_INCREF(PyExc_GreenletExit);
	PyModule_AddObject(m, "GreenletExit", PyExc_GreenletExit);
#ifdef GREENLET_USE_GC
	PyModule_AddObject(m, "GREENLET_USE_GC", PyBool_FromLong(1));
#else
	PyModule_AddObject(m, "GREENLET_USE_GC", PyBool_FromLong(0));
#endif

        /* also publish module-level data as attributes of the greentype. */
	for (p=copy_on_greentype; *p; p++) {
		PyObject* o = PyObject_GetAttrString(m, *p);
		if (!o) continue;
		PyDict_SetItemString(PyGreenlet_Type.tp_dict, *p, o);
		Py_DECREF(o);
	}

	/*
	 * Expose C API
	 */

	/* types */
	_PyGreenlet_API[PyGreenlet_Type_NUM] = (void *) &PyGreenlet_Type;

	/* exceptions */
	_PyGreenlet_API[PyExc_GreenletError_NUM] = (void *) PyExc_GreenletError;
	_PyGreenlet_API[PyExc_GreenletExit_NUM] = (void *) PyExc_GreenletExit;

	/* methods */
	_PyGreenlet_API[PyGreenlet_New_NUM] = (void *) PyGreenlet_New;
	_PyGreenlet_API[PyGreenlet_GetCurrent_NUM] =
		(void *) PyGreenlet_GetCurrent;
	_PyGreenlet_API[PyGreenlet_Throw_NUM] = (void *) PyGreenlet_Throw;
	_PyGreenlet_API[PyGreenlet_Switch_NUM] = (void *) PyGreenlet_Switch;
	_PyGreenlet_API[PyGreenlet_SetParent_NUM] =
		(void *) PyGreenlet_SetParent;

#ifdef GREENLET_USE_PYCAPSULE
	c_api_object = PyCapsule_New((void *) _PyGreenlet_API, "greenlet._C_API", NULL);
#else
	c_api_object = PyCObject_FromVoidPtr((void *) _PyGreenlet_API, NULL);
#endif
	if (c_api_object != NULL)
	{
		PyModule_AddObject(m, "_C_API", c_api_object);
	}

#if PY_MAJOR_VERSION >= 3
	return m;
#endif
}
Beispiel #30
0
void IvrPython::run(){
   FILE* fp;
   int retval;

#ifndef	IVR_PERL
   pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
#endif	//IVR_PERL
//   static PyThreadState* pyMainThreadState;
   fp = fopen((char*)fileName,"r");
   if(fp != NULL){
#ifndef	IVR_PERL
     PyMethodDef extIvrPython[] = {
       // media functions
       {"enqueueMediaFile", ivrEnqueueMediaFile, METH_VARARGS, "ivr: enqueue media file. "
	"filename: string, front : int = 1(default true)  "},
       {"emptyMediaQueue", ivrEmptyMediaQueue, METH_VARARGS, "ivr: empty the media queue."},
       {"startRecording", ivrStartRecording, METH_VARARGS, "ivr: start recording to file. filename : string."},
       {"stopRecording", ivrStopRecording, METH_VARARGS, "ivr: stop recording to file."},
#ifdef IVR_WITH_TTS
       {"say", ivrSay, METH_VARARGS, "ivr tts and enqueue. msg: string, front: boolean  "},
#endif //IVR_WITH_TTS
       // DTMF functions
       {"enableDTMFDetection", ivrEnableDTMFDetection, METH_VARARGS, "enable DTMF detection. "
	"setCallback(onDTMF_FUNC, \"onDTMF\") first!"},
       {"disableDTMFDetection", ivrDisableDTMFDetection, METH_VARARGS, "disable DTMF detection permanently"},
       {"pauseDTMFDetection", ivrPauseDTMFDetection, METH_VARARGS, "pause DTMF detection temporarily, can be resumed"},
       {"resumeDTMFDetection", ivrResumeDTMFDetection, METH_VARARGS, "resume DTMF detection"},

       // informational
       {"getTime", ivrGetTime, METH_VARARGS, "Example Module"},
       {"getFrom", ivrGetFrom, METH_VARARGS, "Example Module"},
       {"getTo", ivrGetTo, METH_VARARGS, "Example Module"},
       {"getFromURI", ivrGetFromURI, METH_VARARGS, "Example Module"},
       {"getToURI", ivrGetToURI, METH_VARARGS, "Example Module"},
       {"getDomain", ivrGetDomain, METH_VARARGS, "Example Module"},

       // call transfer functions
       {"redirect", ivrRedirect, METH_VARARGS, "Example Module"},
       {"dialout", ivrDialout, METH_VARARGS, "Example Module"},

       // setting callbacks
       {"setCallback", setCallback, METH_VARARGS, "Example Module"},

       {"sleep", ivrSleep, METH_VARARGS, "Sleep n seconds, or until wakeUp"},
       {"usleep", ivrUSleep, METH_VARARGS, "Sleep n microseconds, or until wakeUp"},
       {"msleep", ivrmSleep, METH_VARARGS, "Sleep n milliseconds, or until wakeUp"},
       {"wakeUp", ivrWakeUp, METH_VARARGS, "wake Up from sleep"},

       // legacy from old ivr: sequential functions
       {"play", ivrPlay, METH_VARARGS, "play and wait for the end of the file (queue empty)"},
       {"record", ivrRecord, METH_VARARGS, "record maximum of time secs. Parameter: filename : string, timeout = 0 : int"},
       {"playAndDetect", ivrPlayAndDetect, METH_VARARGS, "play and wait for the end of the file (queue empty) or keypress"},
       {"detect", ivrDetect, METH_VARARGS, "detect until timeout Parameter: timeout = 0 : int"},
// for jitter/clock skew generation test only
// DONT CALL THIS FUNCTION
       {"mediaThreadUSleep", ivrMediaThreadUSleep, METH_VARARGS, "let mthr sleep, dont call this function"},

       {NULL, NULL, 0, NULL},
     };

     if(!Py_IsInitialized()){
       DBG("Start" SCRIPT_TYPE "\n");
       Py_Initialize();
       PyEval_InitThreads();
       pyMainThreadState = PyEval_SaveThread();
     }
     DBG("Start new" SCRIPT_TYPE "interpreter\n");
     PyEval_AcquireLock();
//     PyThreadState* pyThreadState;
     if ( (mainInterpreterThreadState = Py_NewInterpreter()) != NULL){

       PyObject* ivrPyInitModule = Py_InitModule(PY_MOD_NAME, extIvrPython);
       PyObject* ivrPythonPointer = PyCObject_FromVoidPtr((void*)this,NULL);
       if (ivrPythonPointer != NULL)
	 PyModule_AddObject(ivrPyInitModule, "ivrPythonPointer", ivrPythonPointer);
       
       Py_tracefunc tmp_t = pythonTrace;
       PyEval_SetTrace(tmp_t, PyCObject_FromVoidPtr((void*)this,NULL));
       if(!PyRun_SimpleFile(fp,(char*)fileName)){
	 fclose(fp);
	 retval = 0;// true;
       }
       else{
            PyErr_Print();
            ERROR("IVR" SCRIPT_TYPE "Error: Failed to run \"%s\"\n", (char*)fileName);
	    retval = -1;// false;
       }

       Py_EndInterpreter(mainInterpreterThreadState);
     }
     else{
       ERROR("IVR" SCRIPT_TYPE "Error: Failed to start new interpreter.\n");
     }
     PyEval_ReleaseLock();
#else	//IVR_PERL

	DBG("Start" SCRIPT_TYPE ", about to alloc\n");
	my_perl_interp = perl_alloc();
	printf("interp is %ld\n", (long) my_perl_interp);
	printf("filename is %s\n", fileName);
	DBG("finished alloc Perl, about to construct Perl\n");
	perl_construct(my_perl_interp);
	PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
	char *embedding[] = { "", (char*)fileName};
	DBG("finished construct Perl, about to parse Perl\n");
	perl_parse(my_perl_interp, xs_init, 2, embedding, (char **)NULL);
	DBG("finished parse Perl, about to run Perl\n");
	SV *pivr = get_sv("Ivr::__ivrpointer__", TRUE);
	DBG("Ivr::__ivrpointer__ is %lx.\n", (unsigned long int) pivr);
	sv_setuv(pivr, (unsigned int) this);
	perl_run(my_perl_interp);
	DBG("finished run Perl, about to sleep 5 seconds to let callback event catch up\n");
	sleep(5);
	DBG("after sleep, about to destruct\n");
	perl_destruct(my_perl_interp);
	DBG("finished destruct Perl, about to free\n");
	perl_free(my_perl_interp);
#endif	//IVR_PERL
   }
   else{
     ERROR("IVR" SCRIPT_TYPE "Error: Can not open file \"%s\"\n",(char*) fileName);
     retval = -1;// false;
   }
   DBG("IVR: run finished. stopping rtp stream...\n");
   pAmSession->rtp_str.pause();
}