コード例 #1
0
PyMODINIT_FUNC PyInit_mathutils(void)
{
	PyObject *mod;
	PyObject *submodule;
	PyObject *sys_modules = PyThreadState_GET()->interp->modules;

	if (PyType_Ready(&vector_Type) < 0)
		return NULL;
	if (PyType_Ready(&matrix_Type) < 0)
		return NULL;
	if (PyType_Ready(&matrix_access_Type) < 0)
		return NULL;
	if (PyType_Ready(&euler_Type) < 0)
		return NULL;
	if (PyType_Ready(&quaternion_Type) < 0)
		return NULL;
	if (PyType_Ready(&color_Type) < 0)
		return NULL;

	mod = PyModule_Create(&M_Mathutils_module_def);
	
	/* each type has its own new() function */
	PyModule_AddObject(mod, vector_Type.tp_name,     (PyObject *)&vector_Type);
	PyModule_AddObject(mod, matrix_Type.tp_name,     (PyObject *)&matrix_Type);
	PyModule_AddObject(mod, euler_Type.tp_name,      (PyObject *)&euler_Type);
	PyModule_AddObject(mod, quaternion_Type.tp_name, (PyObject *)&quaternion_Type);
	PyModule_AddObject(mod, color_Type.tp_name,      (PyObject *)&color_Type);
	
	/* submodule */
	PyModule_AddObject(mod, "geometry",       (submodule = PyInit_mathutils_geometry()));
	/* XXX, python doesnt do imports with this usefully yet
	 * 'from mathutils.geometry import PolyFill'
	 * ...fails without this. */
	PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
	Py_INCREF(submodule);

#ifndef MATH_STANDALONE
	/* Noise submodule */
	PyModule_AddObject(mod, "noise", (submodule = PyInit_mathutils_noise()));
	PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
	Py_INCREF(submodule);

	/* KDTree submodule */
	PyModule_AddObject(mod, "kdtree", (submodule = PyInit_mathutils_kdtree()));
	PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
	Py_INCREF(submodule);
#endif

	mathutils_matrix_row_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_row_cb);
	mathutils_matrix_col_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_col_cb);
	mathutils_matrix_translation_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_translation_cb);

	return mod;
}
コード例 #2
0
int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
    PyObject *d = 0;
    PyObject *cobj = 0;
    union {
        void (*fp)(void);
        void *p;
    } tmp;

    d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
    if (!d)
        goto bad;
    cobj = PyDict_GetItemString(d, funcname);
    if (!cobj) {
        PyErr_Format(PyExc_ImportError,
            "%s does not export expected C function %s",
                PyModule_GetName(module), funcname);
        goto bad;
    }
#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0)
    if (!PyCapsule_IsValid(cobj, sig)) {
        PyErr_Format(PyExc_TypeError,
            "C function %s.%s has wrong signature (expected %s, got %s)",
             PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
        goto bad;
    }
    tmp.p = PyCapsule_GetPointer(cobj, sig);
#else
    {const char *desc, *s1, *s2;
    desc = (const char *)PyCObject_GetDesc(cobj);
    if (!desc)
        goto bad;
    s1 = desc; s2 = sig;
    while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; }
    if (*s1 != *s2) {
        PyErr_Format(PyExc_TypeError,
            "C function %s.%s has wrong signature (expected %s, got %s)",
             PyModule_GetName(module), funcname, sig, desc);
        goto bad;
    }
    tmp.p = PyCObject_AsVoidPtr(cobj);}
#endif
    *f = tmp.fp;
    if (!(*f))
        goto bad;
    Py_DECREF(d);
    return 0;
bad:
    Py_XDECREF(d);
    return -1;
}
コード例 #3
0
ファイル: _yappi.c プロジェクト: sumerc/yappi
static PyObject *
_pycfunction_module_name(PyCFunctionObject *cfn)
{
    PyObject *obj;
    PyObject *name;

    // The __module__ attribute, can be anything
    obj = cfn->m_module;

    if (!obj) {
        // TODO: Is this always correct?
        name = PyStr_FromString("__builtin__");
    } else if (PyStr_Check(obj)) {
        Py_INCREF(obj);
        name = obj;
    } else if (PyModule_Check(obj)) {
        const char *s = PyModule_GetName(obj);
        if (!s) {
            goto error;
        }
        name = PyStr_FromString(s);
    } else {
        // Something else - str(obj)
        name = PyObject_Str(obj);
    }

    return name;

error:
    PyErr_Clear();
    return PyStr_FromString("<unknown>");
}
コード例 #4
0
/* PyModule_AddObject function was introduced in Python 2.0.  The following function
is copied out of Python/modsupport.c in python version 2.3.4 */
static int
PyModule_AddObject(PyObject *m, char *name, PyObject *o)
{
	PyObject *dict;
	if (!PyModule_Check(m)) {
		PyErr_SetString(PyExc_TypeError,
			    "PyModule_AddObject() needs module as first arg");
		return -1;
	}
	if (!o) {
		PyErr_SetString(PyExc_TypeError,
				"PyModule_AddObject() needs non-NULL value");
		return -1;
	}

	dict = PyModule_GetDict(m);
	if (dict == NULL) {
		/* Internal error -- modules must have a dict! */
		PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
			     PyModule_GetName(m));
		return -1;
	}
	if (PyDict_SetItemString(dict, name, o))
		return -1;
	Py_DECREF(o);
	return 0;
}
コード例 #5
0
static PyObject *
normalizeUserObj(PyObject *obj)
{
	PyCFunctionObject *fn;
	if (!PyCFunction_Check(obj)) {
		Py_INCREF(obj);
		return obj;
	}
	/* Replace built-in function objects with a descriptive string
	   because of built-in methods -- keeping a reference to
	   __self__ is probably not a good idea. */
	fn = (PyCFunctionObject *)obj;

	if (fn->m_self == NULL) {
		/* built-in function: look up the module name */
		PyObject *mod = fn->m_module;
		const char *modname;
		if (mod && PyUnicode_Check(mod)) {
			modname = _PyUnicode_AsString(mod);
		}
		else if (mod && PyModule_Check(mod)) {
			modname = PyModule_GetName(mod);
			if (modname == NULL) {
				PyErr_Clear();
				modname = "builtins";
			}
		}
		else {
			modname = "builtins";
		}
		if (strcmp(modname, "builtins") != 0)
			return PyUnicode_FromFormat("<%s.%s>",
						    modname,
						    fn->m_ml->ml_name);
		else
			return PyUnicode_FromFormat("<%s>",
						    fn->m_ml->ml_name);
	}
	else {
		/* built-in method: try to return
			repr(getattr(type(__self__), __name__))
		*/
		PyObject *self = fn->m_self;
		PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name);
		if (name != NULL) {
			PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
			Py_XINCREF(mo);
			Py_DECREF(name);
			if (mo != NULL) {
				PyObject *res = PyObject_Repr(mo);
				Py_DECREF(mo);
				if (res != NULL)
					return res;
			}
		}
		PyErr_Clear();
		return PyUnicode_FromFormat("<built-in method %s>",
					    fn->m_ml->ml_name);
	}
}
コード例 #6
0
ファイル: bpy_internal_import.c プロジェクト: 244xiao/blender
PyObject *bpy_text_reimport(PyObject *module, int *found)
{
	Text *text;
	const char *name;
	char *filepath;
	char *buf = NULL;
//XXX	Main *maggie = bpy_import_main ? bpy_import_main:G.main;
	Main *maggie = bpy_import_main;
	
	if (!maggie) {
		printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
		return NULL;
	}
	
	*found = 0;
	
	/* get name, filename from the module itself */
	if ((name = PyModule_GetName(module)) == NULL)
		return NULL;

	if ((filepath = (char *)PyModule_GetFilename(module)) == NULL)
		return NULL;

	/* look up the text object */
	text = BLI_findstring(&maggie->text, BLI_path_basename(filepath), offsetof(ID, name) + 2);

	/* uh-oh.... didn't find it */
	if (!text)
		return NULL;
	else
		*found = 1;

	/* if previously compiled, free the object */
	/* (can't see how could be NULL, but check just in case) */ 
	if (text->compiled) {
		Py_DECREF((PyObject *)text->compiled);
	}

	/* compile the buffer */
	buf = txt_to_buf(text);
	text->compiled = Py_CompileString(buf, text->id.name + 2, Py_file_input);
	MEM_freeN(buf);

	/* if compile failed.... return this error */
	if (PyErr_Occurred()) {
		PyErr_Print();
		PyErr_Clear();
		PySys_SetObject("last_traceback", NULL);
		free_compiled_text(text);
		return NULL;
	}

	/* make into a module */
	return PyImport_ExecCodeModule((char *)name, text->compiled);
}
コード例 #7
0
ファイル: ofxPy.cpp プロジェクト: satoruhiga/ofxPy
bool Context::import(py::module m)
{
	if (!m)
		return false;
	
	string name = PyModule_GetName(m.ptr());
	if (!name.empty())
	{
		py_global[name.c_str()] = m;
	}
	
	return true;
}
コード例 #8
0
PyObject *BPyInit_idprop(void)
{
    PyObject *mod;
    PyObject *submodule;
    PyObject *sys_modules = PyThreadState_GET()->interp->modules;

    mod = PyModule_Create(&IDProp_module_def);

    /* idprop.types */
    PyModule_AddObject(mod, "types", (submodule = BPyInit_idprop_types()));
    PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
    Py_INCREF(submodule);

    return mod;
}
コード例 #9
0
PyObject *bpy_text_reimport(PyObject *module, int *found)
{
	Text *text;
	const char *name;
	const char *filepath;
//XXX	Main *maggie = bpy_import_main ? bpy_import_main:G.main;
	Main *maggie = bpy_import_main;
	
	if (!maggie) {
		printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
		return NULL;
	}
	
	*found = 0;
	
	/* get name, filename from the module itself */
	if ((name = PyModule_GetName(module)) == NULL)
		return NULL;

	{
		PyObject *module_file = PyModule_GetFilenameObject(module);
		if (module_file == NULL) {
			return NULL;
		}
		filepath = _PyUnicode_AsString(module_file);
		Py_DECREF(module_file);
		if (filepath == NULL) {
			return NULL;
		}
	}

	/* look up the text object */
	text = BLI_findstring(&maggie->text, BLI_path_basename(filepath), offsetof(ID, name) + 2);

	/* uh-oh.... didn't find it */
	if (!text)
		return NULL;
	else
		*found = 1;

	if (bpy_text_compile(text) == false) {
		return NULL;
	}

	/* make into a module */
	return PyImport_ExecCodeModule(name, text->compiled);
}
コード例 #10
0
ファイル: cimport.c プロジェクト: pganti/micheles
PyObject *
reload_module(PyObject *m)
{
	PyObject *modules = PyImport_GetModuleDict();
	PyObject *path = NULL;
	char *name, *subname;

	if (m == NULL || !PyModule_Check(m)) {
		PyErr_SetString(PyExc_TypeError,
				"reload_module() argument must be module");
		return NULL;
	}
	name = PyModule_GetName(m);
	if (name == NULL)
		return NULL;
	if (m != PyDict_GetItemString(modules, name)) {
		PyErr_Format(PyExc_ImportError,
			     "reload(): module %.200s not in sys.modules",
			     name);
		return NULL;
	}
	subname = strrchr(name, '.');
	if (subname == NULL)
		subname = name;
	else {
		PyObject *parentname, *parent;
		parentname = PyString_FromStringAndSize(name, (subname-name));
		if (parentname == NULL)
			return NULL;
		parent = PyDict_GetItem(modules, parentname);
		Py_DECREF(parentname);
		if (parent == NULL) {
			PyErr_Format(PyExc_ImportError,
			    "reload(): parent %.200s not in sys.modules",
			    name);
			return NULL;
		}
		subname++;
		path = PyObject_GetAttrString(parent, "__path__");
		if (path == NULL)
			PyErr_Clear();
	}
	m = call_find_load(name, subname, path);
	Py_XDECREF(path);
	return m;
}
コード例 #11
0
ファイル: moduleobject.c プロジェクト: MatiasNAmendola/cleese
static PyObject *
module_repr(PyModuleObject *m)
{
	char *name;
	char *filename;

	name = PyModule_GetName((PyObject *)m);
	if (name == NULL) {
		PyErr_Clear();
		name = "?";
	}
	filename = PyModule_GetFilename((PyObject *)m);
	if (filename == NULL) {
		PyErr_Clear();
		return PyString_FromFormat("<module '%s' (built-in)>", name);
	}
	return PyString_FromFormat("<module '%s' from '%s'>", name, filename);
}
コード例 #12
0
ファイル: stub-gen.c プロジェクト: fatman2021/python-corba
static void
add_stub_to_container(CORBA_TypeCode tc, const gchar *name, PyObject *stub)
{
    PyObject *container;
    gchar *pyname;

    container = _pymatecorba_get_container(tc->repo_id, FALSE);
    if (!container)
        return;

    pyname = _pymatecorba_escape_name(name);
    if (PyType_Check(container)) {
        PyObject *container_dict = ((PyTypeObject *)container)->tp_dict;

        PyDict_SetItemString(container_dict, pyname, stub);
    } else {
        PyObject_SetAttrString(container, pyname, stub);
    }
    g_free(pyname);
    if (PyErr_Occurred())
        PyErr_Clear();

    /* set __module__ if it is not an alias ... */
    if (tc->kind != CORBA_tk_alias &&
            (PyType_Check(stub) || PyClass_Check(stub))) {
        PyObject *module = NULL;

        if (PyModule_Check(container)) {
            const gchar *name;
            name = PyModule_GetName(container);
            if (name) module = PyString_FromString(name);
        } else {
            module = PyObject_GetAttrString(container, "__module__");
        }
        if (module) {
            PyObject_SetAttrString(stub, "__module__", module);
            Py_DECREF(module);
        }
    }

    Py_DECREF(container);
}
コード例 #13
0
static PyObject *
module_repr(PyModuleObject *m)
{
    const char *name;
    PyObject *filename, *repr;

    name = PyModule_GetName((PyObject *)m);
    if (name == NULL) {
        PyErr_Clear();
        name = "?";
    }
    filename = PyModule_GetFilenameObject((PyObject *)m);
    if (filename == NULL) {
        PyErr_Clear();
        return PyUnicode_FromFormat("<module '%s' (built-in)>", name);
    }
    repr = PyUnicode_FromFormat("<module '%s' from '%U'>", name, filename);
    Py_DECREF(filename);
    return repr;
}
コード例 #14
0
static PyObject *
module_dir(PyObject *self, PyObject *args)
{
    _Py_IDENTIFIER(__dict__);
    PyObject *result = NULL;
    PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);

    if (dict != NULL) {
        if (PyDict_Check(dict))
            result = PyDict_Keys(dict);
        else {
            const char *name = PyModule_GetName(self);
            if (name)
                PyErr_Format(PyExc_TypeError,
                             "%.200s.__dict__ is not a dictionary",
                             name);
        }
    }

    Py_XDECREF(dict);
    return result;
}
コード例 #15
0
ファイル: moduleobject.c プロジェクト: 3lnc/cpython
int
PyModule_ExecDef(PyObject *module, PyModuleDef *def)
{
    PyModuleDef_Slot *cur_slot;
    const char *name;
    int ret;

    name = PyModule_GetName(module);
    if (name == NULL) {
        return -1;
    }

    if (def->m_size >= 0) {
        PyModuleObject *md = (PyModuleObject*)module;
        if (md->md_state == NULL) {
            /* Always set a state pointer; this serves as a marker to skip
             * multiple initialization (importlib.reload() is no-op) */
            md->md_state = PyMem_MALLOC(def->m_size);
            if (!md->md_state) {
                PyErr_NoMemory();
                return -1;
            }
            memset(md->md_state, 0, def->m_size);
        }
    }

    if (def->m_slots == NULL) {
        return 0;
    }

    for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
        switch (cur_slot->slot) {
            case Py_mod_create:
                /* handled in PyModule_FromDefAndSpec2 */
                break;
            case Py_mod_exec:
                ret = ((int (*)(PyObject *))cur_slot->value)(module);
                if (ret != 0) {
                    if (!PyErr_Occurred()) {
                        PyErr_Format(
                            PyExc_SystemError,
                            "execution of module %s failed without setting an exception",
                            name);
                    }
                    return -1;
                }
                if (PyErr_Occurred()) {
                    PyErr_Format(
                        PyExc_SystemError,
                        "execution of module %s raised unreported exception",
                        name);
                    return -1;
                }
                break;
            default:
                PyErr_Format(
                    PyExc_SystemError,
                    "module %s initialized with unknown slot %i",
                    name, cur_slot->slot);
                return -1;
        }
    }
    return 0;
}
コード例 #16
0
ファイル: python_support.c プロジェクト: cbourgeois/gnatcoll
#endif  /* python 3.x */

// Adds a new method to the class 'class'.
// 'module' is the module to which the class belongs, and is used to set
//    the __module__ attribute of the new method.
// 'def' described the C function that will be called when the function is
//    executed in python.
// 'data' is data to pass from C->Python->C (generally wrapped in a PyCapsule).
//    It will be pass as the "Self" argument to First_Level.

void ada_py_add_method
   (PyMethodDef* def, PyObject* data, PyObject* class, PyObject* module)
{
  PyObject* cfunc = PyCFunction_NewEx
    (def, data, PyUnicode_FromString (PyModule_GetName (module)));

#if PY_MAJOR_VERSION >= 3
  PyObject* method = PyDescr_NewAdaMethod
    ((PyTypeObject*)class, cfunc, def->ml_name);
#else
  PyObject* method = PyMethod_New (cfunc, NULL, class);
#endif

  PyObject_SetAttrString (class, def->ml_name, method);
  Py_DECREF (method);
};

/*****************************************************************************/

int
コード例 #17
0
ファイル: _lsprof.c プロジェクト: andrcmdr/unladen-swallow
static PyObject *
normalizeUserObj(PyObject *obj)
{
	/* Replace built-in function objects with a descriptive string
	   because of built-in methods -- keeping a reference to
	   __self__ is probably not a good idea. */
	PyCFunctionObject *fn = (PyCFunctionObject *)obj;

	if (PyCFunction_Check(obj) && fn->m_self == NULL) {
		/* built-in function: look up the module name */
		PyObject *mod = fn->m_module;
		char *modname;
		if (mod && PyString_Check(mod)) {
			modname = PyString_AS_STRING(mod);
		}
		else if (mod && PyModule_Check(mod)) {
			modname = PyModule_GetName(mod);
			if (modname == NULL) {
				PyErr_Clear();
				modname = "__builtin__";
			}
		}
		else {
			modname = "__builtin__";
		}
		if (strcmp(modname, "__builtin__") != 0)
			return PyString_FromFormat("<%s.%s>",
						   modname,
						   fn->m_ml->ml_name);
		else
			return PyString_FromFormat("<%s>",
						   fn->m_ml->ml_name);
	}
	else if (PyCFunction_Check(obj) || PyMethodDescr_Check(obj)) {
		/* built-in method: try to return
			repr(getattr(type(__self__), __name__))
		*/
		PyTypeObject *type;
		const char *name;
		PyObject *name_obj;
		if (PyCFunction_Check(obj)) {
			type = Py_TYPE(fn->m_self);
			name = fn->m_ml->ml_name;
		}
		else {
			PyMethodDescrObject *descr = (PyMethodDescrObject *)obj;
			type = descr->d_type;
			name = descr->d_method->ml_name;
		}
		name_obj = PyString_FromString(name);
		if (name_obj != NULL) {
			PyObject *mo = _PyType_Lookup(type, name_obj);
			Py_XINCREF(mo);
			Py_DECREF(name_obj);
			if (mo != NULL) {
				PyObject *res = PyObject_Repr(mo);
				Py_DECREF(mo);
				if (res != NULL)
					return res;
			}
		}
		PyErr_Clear();
		return PyString_FromFormat("<built-in method %s>", name);
	}
	else {
		Py_INCREF(obj);
		return obj;
	}
}
コード例 #18
0
PyObject *
_pymatecorba_get_container(const gchar *repo_id, gboolean is_poa)
{
    const gchar *slash;
    PyObject *parent = NULL;

    if (strncmp(repo_id, "IDL:", 4) != 0) {
	g_warning("bad repo_id %s", repo_id);
	return NULL;
    }
    repo_id += 4;

    /* get rid of omg.org prefix ... */
    if (strncmp(repo_id, "omg.org/", 8) == 0)
	repo_id += 8;

    while ((slash = strchr(repo_id, '/')) != NULL) {
	gchar *component = g_strndup(repo_id, slash - repo_id);

	/* check if we can already find the component */
	if (parent) {
	    PyObject *attr = PyObject_GetAttrString(parent, component);
	    gchar *escaped_name, *importname;

	    if (attr) {
		Py_DECREF(parent);
		parent = attr;
		goto cont;
	    }
	    PyErr_Clear();
	    if (!PyModule_Check(parent)) {
		g_warning("parent not a module, and component not found");
		g_free(component);
		Py_DECREF(parent);
		parent = NULL;
		break;
	    }
	    escaped_name = _pymatecorba_escape_name(component);
	    importname = g_strconcat(PyModule_GetName(parent),
				     ".", escaped_name, NULL);
	    g_free(escaped_name);
	    attr = PyImport_ImportModule(importname);
	    if (attr) {
		Py_DECREF(parent);
		parent = attr;
		g_free(importname);
		goto cont;
	    }
	    PyErr_Clear();
	    attr = Py_InitModule(importname, fake_module_methods);
	    g_free(importname);
	    if (!attr) {
		g_warning("could not construct module");
		g_free(component);
		Py_DECREF(parent);
		parent = NULL;
		break;
	    }
	    Py_INCREF(attr); /* you don't own the return of Py_InitModule */
	    PyObject_SetAttrString(parent, component, attr);
	    Py_DECREF(parent);
	    parent = attr;
	} else {
	    PyObject *mod;
	    gchar *modname;

	    if (is_poa)
		modname = g_strconcat(component, "__POA", NULL);
	    else
		modname = _pymatecorba_escape_name(component);
	    mod = PyImport_ImportModule(modname);
	    if (mod) {
		g_free(modname);
		parent = mod;
		goto cont;
	    }
	    PyErr_Clear();
	    mod = Py_InitModule(modname, fake_module_methods);
	    g_free(modname);
	    if (!mod) {
		g_warning("could not construct module");
		g_free(component);
		break;
	    }
	    parent = mod;
	    Py_INCREF(parent);
	}
    cont:
	g_free(component);
	repo_id = &slash[1];
    }
    if (!parent) {
	if (is_poa)
	    parent = PyImport_ImportModule("_GlobalIDL__POA");
	else
	    parent = PyImport_ImportModule("_GlobalIDL");
	if (!parent) {
	    PyErr_Clear();
	    if (is_poa)
		parent = Py_InitModule("_GlobalIDL__POA", fake_module_methods);
	    else
		parent = Py_InitModule("_GlobalIDL", fake_module_methods);
	    if (!parent) {
		g_warning("could not create _GlobalIDL module");
	    } else
                Py_INCREF(parent); /* you don't own the return of Py_InitModule */
	}
    }
    return parent;
}
コード例 #19
0
ファイル: PyConstants.cpp プロジェクト: FeuernD/OpenColorIO
 void AddConstantsModule(PyObject *enclosingModule)
 {
     // Add sub-module
     std::string moduleName = PyModule_GetName(enclosingModule);
     moduleName += ".Constants";
     
     PyObject * m = Py_InitModule3(const_cast<char*>(moduleName.c_str()),
         LocalModuleMethods, CONSTANTS__DOC__);
     Py_INCREF(m);
     
     // Add Module Constants
     PyModule_AddStringConstant(m, "LOGGING_LEVEL_NONE",
         const_cast<char*>(LoggingLevelToString(LOGGING_LEVEL_NONE)));
     PyModule_AddStringConstant(m, "LOGGING_LEVEL_WARNING",
         const_cast<char*>(LoggingLevelToString(LOGGING_LEVEL_WARNING)));
     PyModule_AddStringConstant(m, "LOGGING_LEVEL_INFO",
         const_cast<char*>(LoggingLevelToString(LOGGING_LEVEL_INFO)));
     PyModule_AddStringConstant(m, "LOGGING_LEVEL_UNKNOWN",
         const_cast<char*>(LoggingLevelToString(LOGGING_LEVEL_UNKNOWN)));
     
     PyModule_AddStringConstant(m, "TRANSFORM_DIR_UNKNOWN",
         const_cast<char*>(TransformDirectionToString(TRANSFORM_DIR_UNKNOWN)));
     PyModule_AddStringConstant(m, "TRANSFORM_DIR_FORWARD",
         const_cast<char*>(TransformDirectionToString(TRANSFORM_DIR_FORWARD)));
     PyModule_AddStringConstant(m, "TRANSFORM_DIR_INVERSE",
         const_cast<char*>(TransformDirectionToString(TRANSFORM_DIR_INVERSE)));
     
     PyModule_AddStringConstant(m, "COLORSPACE_DIR_UNKNOWN",
         const_cast<char*>(ColorSpaceDirectionToString(COLORSPACE_DIR_UNKNOWN)));
     PyModule_AddStringConstant(m, "COLORSPACE_DIR_TO_REFERENCE",
         const_cast<char*>(ColorSpaceDirectionToString(COLORSPACE_DIR_TO_REFERENCE)));
     PyModule_AddStringConstant(m, "COLORSPACE_DIR_FROM_REFERENCE",
         const_cast<char*>(ColorSpaceDirectionToString(COLORSPACE_DIR_FROM_REFERENCE)));
     
     PyModule_AddStringConstant(m, "BIT_DEPTH_UNKNOWN",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_UNKNOWN)));
     PyModule_AddStringConstant(m, "BIT_DEPTH_UINT8",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT8)));
     PyModule_AddStringConstant(m, "BIT_DEPTH_UINT10",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT10)));
     PyModule_AddStringConstant(m, "BIT_DEPTH_UINT12",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT12)));
     PyModule_AddStringConstant(m, "BIT_DEPTH_UINT14",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT14)));
     PyModule_AddStringConstant(m, "BIT_DEPTH_UINT16",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT16)));
     PyModule_AddStringConstant(m, "BIT_DEPTH_UINT32",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT32)));
     PyModule_AddStringConstant(m, "BIT_DEPTH_F16",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_F16)));
     PyModule_AddStringConstant(m, "BIT_DEPTH_F32",
         const_cast<char*>(BitDepthToString(BIT_DEPTH_F32)));
     
     PyModule_AddStringConstant(m, "ALLOCATION_UNKNOWN",
         const_cast<char*>(AllocationToString(ALLOCATION_UNKNOWN)));
     PyModule_AddStringConstant(m, "ALLOCATION_UNIFORM",
         const_cast<char*>(AllocationToString(ALLOCATION_UNIFORM)));
     PyModule_AddStringConstant(m, "ALLOCATION_LG2",
         const_cast<char*>(AllocationToString(ALLOCATION_LG2)));
     
     PyModule_AddStringConstant(m, "INTERP_UNKNOWN",
         const_cast<char*>(InterpolationToString(INTERP_UNKNOWN)));
     PyModule_AddStringConstant(m, "INTERP_NEAREST",
         const_cast<char*>(InterpolationToString(INTERP_NEAREST)));
     PyModule_AddStringConstant(m, "INTERP_LINEAR",
         const_cast<char*>(InterpolationToString(INTERP_LINEAR)));
     PyModule_AddStringConstant(m, "INTERP_TETRAHEDRAL",
         const_cast<char*>(InterpolationToString(INTERP_TETRAHEDRAL)));
     PyModule_AddStringConstant(m, "INTERP_BEST",
         const_cast<char*>(InterpolationToString(INTERP_BEST)));
     
     PyModule_AddStringConstant(m, "GPU_LANGUAGE_UNKNOWN",
         const_cast<char*>(GpuLanguageToString(GPU_LANGUAGE_UNKNOWN)));
     PyModule_AddStringConstant(m, "GPU_LANGUAGE_CG",
         const_cast<char*>(GpuLanguageToString(GPU_LANGUAGE_CG)));
     PyModule_AddStringConstant(m, "GPU_LANGUAGE_GLSL_1_0",
         const_cast<char*>(GpuLanguageToString(GPU_LANGUAGE_GLSL_1_0)));
     PyModule_AddStringConstant(m, "GPU_LANGUAGE_GLSL_1_3",
         const_cast<char*>(GpuLanguageToString(GPU_LANGUAGE_GLSL_1_3)));
     
     PyModule_AddStringConstant(m, "ROLE_DEFAULT", const_cast<char*>(ROLE_DEFAULT));
     PyModule_AddStringConstant(m, "ROLE_REFERENCE", const_cast<char*>(ROLE_REFERENCE));
     PyModule_AddStringConstant(m, "ROLE_DATA", const_cast<char*>(ROLE_DATA));
     PyModule_AddStringConstant(m, "ROLE_COLOR_PICKING", const_cast<char*>(ROLE_COLOR_PICKING));
     PyModule_AddStringConstant(m, "ROLE_SCENE_LINEAR", const_cast<char*>(ROLE_SCENE_LINEAR));
     PyModule_AddStringConstant(m, "ROLE_COMPOSITING_LOG", const_cast<char*>(ROLE_COMPOSITING_LOG));
     PyModule_AddStringConstant(m, "ROLE_COLOR_TIMING", const_cast<char*>(ROLE_COLOR_TIMING));
     PyModule_AddStringConstant(m, "ROLE_TEXTURE_PAINT", const_cast<char*>(ROLE_TEXTURE_PAINT));
     PyModule_AddStringConstant(m, "ROLE_MATTE_PAINT", const_cast<char*>(ROLE_MATTE_PAINT));
     
     // Add the module
     PyModule_AddObject(enclosingModule, "Constants", m);
 }
コード例 #20
0
void PyHelpersTest::RunTests()
{
  // Test py::Ptr construction
  {
    {
      // NULL pointer
      PyObject * p  = NULL;
      SHOULDFAIL(py::Ptr(p, /* allowNULL: */false));

      py::Ptr pp1(p, /* allowNULL: */true);
      TEST((PyObject *)pp1 == NULL);
      TEST(pp1.isNULL());
    }

    // Non-NULL pointer
    {
      PyObject * p = PyTuple_New(1);
      py::Ptr pp2(p);
      TEST(!pp2.isNULL());
      TEST((PyObject *)pp2 == p);
      pp2.release();
      TEST(pp2.isNULL());
      Py_DECREF(p);
    }
    
    // assign
    {
      PyObject * p = PyTuple_New(1);
      TEST(p->ob_refcnt == 1);
      py::Ptr pp(NULL, /* allowNULL */ true);
      TEST(pp.isNULL());
      NTA_DEBUG << "*** Before assign";
      pp.assign(p);
      NTA_DEBUG << "*** After assign";
      TEST(p->ob_refcnt == 2);
      TEST(!(pp.isNULL()));
      Py_DECREF(p);
      TEST(p->ob_refcnt == 1);
    }
  }

  // py::String
  {
    py::String ps1(std::string("123"));
    TEST(PyString_Check(ps1) != 0);

    py::String ps2("123", size_t(3));
    TEST(PyString_Check(ps2) != 0);

    py::String ps3("123");
    TEST(PyString_Check(ps3) != 0);

    std::string s1(PyString_AsString(ps1));
    std::string s2(PyString_AsString(ps2));
    std::string s3(PyString_AsString(ps3));
    std::string expected("123");
    TEST(s1 == expected);
    TEST(s2 == expected);
    TEST(s3 == expected);
  
    TEST(std::string(ps1) == expected);
    TEST(std::string(ps2) == expected);
    TEST(std::string(ps3) == expected);

    PyObject * p = PyString_FromString("777");
    py::String ps4(p);
    TEST(std::string(ps4) == std::string("777"));
  }

  // py::Int
  {
    py::Int n1(-5);
    py::Int n2(-6666);
    py::Int n3(long(0));
    py::Int n4(555);
    py::Int n5(6666);
    
    TEST(n1 == -5);
    int x = n2; 
    int expected = -6666;
    TEST(x == expected);
    TEST(n3 == 0);
    TEST(n4 == 555);
    x = n5;
    expected = 6666;
    TEST(x == expected);
  }

  // py::Long
  {
    py::Long n1(-5);
    py::Long n2(-66666666);
    py::Long n3(long(0));
    py::Long n4(555);
    py::Long n5(66666666);
    
    TEST(n1 == -5);
    long x = n2; 
    long expected = -66666666;
    TEST(x == expected);
    TEST(n3 == 0);
    TEST(n4 == 555);
    x = n5;
    expected = 66666666;
    TEST(x == expected);
  }

  // py::UnsignedLong
  {
    py::UnsignedLong n1((unsigned long)(-5));
    py::UnsignedLong n2((unsigned long)(-66666666));
    py::UnsignedLong n3((unsigned long)(0));
    py::UnsignedLong n4(555);
    py::UnsignedLong n5(66666666);
    
    TEST(n1 == (unsigned long)(-5));
    TEST(n2 == (unsigned long)(-66666666));
    TEST(n3 == 0);
    TEST(n4 == 555);
    TEST(n5 == 66666666);
  }

  // py::Float
  {
    TEST(py::Float::getMax() == std::numeric_limits<double>::max());
    TEST(py::Float::getMin() == std::numeric_limits<double>::min());

    py::Float max(std::numeric_limits<double>::max());
    py::Float min(std::numeric_limits<double>::min());
    py::Float n1(-0.5);
    py::Float n2(double(0));
    py::Float n3(333.555);
    py::Float n4(0.02);
    py::Float n5("0.02");
    
    TEST(max == py::Float::getMax());
    TEST(min == py::Float::getMin());
    TEST(n1 == -0.5);
    TEST(n2 == 0);
    TEST(n3 == 333.555);
    TEST(n4 == 0.02);
    TEST(n5 == 0.02);
  }

  // py::Tuple
  {
    py::String s1("item_1");
    py::String s2("item_2");

    // Empty tuple
    {
      py::Tuple empty;
      TEST(PyTuple_Check(empty) != 0);
      TEST(empty.getCount() == 0);
      
      SHOULDFAIL(empty.setItem(0, s1));
      SHOULDFAIL(empty.getItem(0));
    }

    // One item tuple
    {
      py::Tuple t1(1);
      TEST(PyTuple_Check(t1) != 0);
      TEST(t1.getCount() == 1);

      t1.setItem(0, s1);
      py::String item1(t1.getItem(0));
      TEST(std::string(item1) == std::string(s1));
      
      py::String fastItem1(t1.fastGetItem(0));
      TEST(std::string(fastItem1) == std::string(s1));
      fastItem1.release();
      
      SHOULDFAIL(t1.setItem(1, s2));
      SHOULDFAIL(t1.getItem(1));

      TEST(t1.getCount() == 1);
    }

    // 2 items tuple
    {
      py::Tuple t2(2);
      TEST(PyTuple_Check(t2) != 0);
      TEST(t2.getCount() == 2);

      t2.setItem(0, s1);
      py::String item1(t2.getItem(0));
      TEST(std::string(item1) == std::string(s1));
      py::String fastItem1(t2.fastGetItem(0));
      TEST(std::string(fastItem1) == std::string(s1));
      fastItem1.release();

      t2.setItem(1, s2);
      py::String item2(t2.getItem(1));
      TEST(std::string(item2) == std::string(s2));
      py::String fastItem2(t2.fastGetItem(1));
      TEST(std::string(fastItem2) == std::string(s2));
      fastItem2.release();


      SHOULDFAIL(t2.setItem(2, s2));
      SHOULDFAIL(t2.getItem(2));

      TEST(t2.getCount() == 2);
    }
  }

  // py::List
  {
    py::String s1("item_1");
    py::String s2("item_2");

    // Empty list
    {
      py::List empty;
      TEST(PyList_Check(empty) != 0);
      TEST(empty.getCount() == 0);
      
      SHOULDFAIL(empty.setItem(0, s1));
      SHOULDFAIL(empty.getItem(0));
    }

    // One item list
    {
      py::List t1;
      TEST(PyList_Check(t1) != 0);
      TEST(t1.getCount() == 0);

      t1.append(s1);
      py::String item1(t1.getItem(0));
      TEST(std::string(item1) == std::string(s1));
      py::String fastItem1(t1.fastGetItem(0));
      TEST(std::string(fastItem1) == std::string(s1));
      fastItem1.release();

      TEST(t1.getCount() == 1);
      TEST(std::string(item1) == std::string(s1));
      
      SHOULDFAIL(t1.getItem(1));
    }

    // Two items list
    {
      py::List t2;
      TEST(PyList_Check(t2) != 0);
      TEST(t2.getCount() == 0);

      t2.append(s1);
      py::String item1(t2.getItem(0));
      TEST(std::string(item1) == std::string(s1));
      py::String fastItem1(t2.fastGetItem(0));
      TEST(std::string(fastItem1) == std::string(s1));
      fastItem1.release();

      t2.append(s2);
      TEST(t2.getCount() == 2);
      
      py::String item2(t2.getItem(1));
      TEST(std::string(item2) == std::string(s2));
      py::String fastItem2(t2.fastGetItem(1));
      TEST(std::string(fastItem2) == std::string(s2));
      fastItem2.release();


      SHOULDFAIL(t2.getItem(2));
    }
  }

  // py::Dict
  {
    // Empty dict
    {
      py::Dict d;
      TEST(PyDict_Size(d) == 0);

      TEST(d.getItem("blah") == NULL);
    }

    // Failed External PyObject *
    {
      // NULL object
      SHOULDFAIL(py::Dict(NULL));

      // Wrong type (must be a dictionary)
      py::String s("1234");
      try
      {
        py::Dict d(s.release());
        NTA_THROW << "py::Dict d(s) Should fail!!!";
      }
      catch(...)
      {
      }
      // SHOULDFAIL fails to fail :-)
      //SHOULDFAIL(py::Dict(s));
    }

    // Successful external PyObject *
    {

      PyObject * p = PyDict_New();
      PyDict_SetItem(p, py::String("1234"), py::String("5678"));
      
      py::Dict d(p);

      TEST(PyDict_Contains(d, py::String("1234")) == 1);

      PyDict_SetItem(d, py::String("777"), py::String("999"));

      TEST(PyDict_Contains(d, py::String("777")) == 1);

    }
    
    // getItem with default (exisiting and non-exisitng key)
    {
      py::Dict d;
      d.setItem("A", py::String("AAA"));

      PyObject * defaultItem = (PyObject *)123;
      
      py::String A(d.getItem("A"));             
      TEST(std::string(A) == std::string("AAA"));

      // No "B" in the dict, so expect to get the default item
      PyObject * B = (d.getItem("B", defaultItem));
      TEST(B == defaultItem);

      PyDict_SetItem(d, py::String("777"), py::String("999"));
      TEST(PyDict_Contains(d, py::String("777")) == 1);
    }
    
    
    //NTA_DEBUG << ss << ": " << ss->ob_refcnt;
  }

  // py::Module
  {
    py::Module module("sys");
    TEST(std::string(PyModule_GetName(module)) == std::string("sys"));
  }

  // py::Class
  {
    py::Class c("datetime", "date");
  }

  // py::Instance
  {
    
    py::Tuple args(3);
    args.setItem(0, py::Long(2000));
    args.setItem(1, py::Long(11));
    args.setItem(2, py::Long(5));
    py::Instance date("datetime", "date", args, py::Dict());

    // Test invoke()
    {
      py::String result(date.invoke("__str__", py::Tuple(), py::Dict()));
      std::string res((const char *)result);
      std::string expected("2000-11-05");
      TEST(res == expected);
    }

    // Test hasAttr()
    {
      py::String result(date.invoke("__str__", py::Tuple(), py::Dict()));
      std::string res((const char *)result);
      std::string expected("2000-11-05");
      TEST(!(date.hasAttr("No such attribute")));
      TEST(date.hasAttr("year"));
    }

    // Test getAttr()
    {
      py::Int year(date.getAttr("year"));
      TEST(2000 == long(year));
    }

    // Test toString()
    {
      std::string res((const char *)py::String(date.toString()));
      std::string expected("2000-11-05");
      TEST(res == expected);
    }
  }

  // Test custom exception
  {
    py::Tuple args(1);
    args.setItem(0, py::String("error message!"));
    py::Instance e(PyExc_RuntimeError, args);
    e.setAttr("traceback", py::String("traceback!!!"));

    PyErr_SetObject(PyExc_RuntimeError, e);

    try
    {
      py::checkPyError(0);
    }
    catch (const nta::Exception & e)
    {
      NTA_DEBUG << e.getMessage();
    }
  }
}
コード例 #21
0
static PyObject *
normalizeUserObj(PyObject *obj)
{
    PyCFunctionObject *fn;
    if (!PyCFunction_Check(obj)) {
        Py_INCREF(obj);
        return obj;
    }
    /* Replace built-in function objects with a descriptive string
       because of built-in methods -- keeping a reference to
       __self__ is probably not a good idea. */
    fn = (PyCFunctionObject *)obj;

    if (fn->m_self == NULL) {
        /* built-in function: look up the module name */
        PyObject *mod = fn->m_module;
        const char *modname;
        if (mod && PyUnicode_Check(mod)) {
            /* XXX: The following will truncate module names with embedded
             * null-characters.  It is unlikely that this can happen in
             * practice and the concequences are not serious enough to
             * introduce extra checks here.
             */
            modname = _PyUnicode_AsString(mod);
            if (modname == NULL) {
                modname = "<encoding error>";
                PyErr_Clear();
            }
        }
        else if (mod && PyModule_Check(mod)) {
            modname = PyModule_GetName(mod);
            if (modname == NULL) {
                PyErr_Clear();
                modname = "builtins";
            }
        }
        else {
            modname = "builtins";
        }
        if (strcmp(modname, "builtins") != 0)
            return PyUnicode_FromFormat("<%s.%s>",
                                        modname,
                                        fn->m_ml->ml_name);
        else
            return PyUnicode_FromFormat("<%s>",
                                        fn->m_ml->ml_name);
    }
    else {
        /* built-in method: try to return
            repr(getattr(type(__self__), __name__))
        */
        PyObject *self = fn->m_self;
        PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name);
        if (name != NULL) {
            PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
            Py_XINCREF(mo);
            Py_DECREF(name);
            if (mo != NULL) {
                PyObject *res = PyObject_Repr(mo);
                Py_DECREF(mo);
                if (res != NULL)
                    return res;
            }
        }
        PyErr_Clear();
        return PyUnicode_FromFormat("<built-in method %s>",
                                    fn->m_ml->ml_name);
    }
}