Extending embedded Python: Adding single methods

Torsten Bronger bronger at physik.rwth-aachen.de
Wed Mar 8 23:31:56 CET 2006


Hallöchen!

Thomas Heller <theller at python.net> writes:

> Torsten Bronger wrote:
>
>> [...]  However, is there a way to avoid this dummy "pp3" module
>> and add the C++ functions directy to the main namespace in the
>> Python script?
>
> Yes.  You can import __builtin__, and add methods to it.  This is
> a snippet from the bdist_wininst code, which embeds Python:
>
> http://svn.python.org/view/python/trunk/PC/bdist_wininst/install.c?rev=38414&view=markup
>
> PyMethodDef meth[] = {
> 	{"create_shortcut", CreateShortcut, METH_VARARGS, NULL},
> 	{"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL},
> 	{"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL},
> 	{"file_created", FileCreated, METH_VARARGS, NULL},
> 	{"directory_created", DirectoryCreated, METH_VARARGS, NULL},
> 	{"message_box", PyMessageBox, METH_VARARGS, NULL},
> };
>
>
> ...
> 	mod = PyImport_ImportModule("__builtin__");
> 	if (mod) {
> 		int i;
> 		for (i = 0; i < DIM(meth); ++i) {
> 			PyObject_SetAttrString(mod, meth[i].ml_name,
> 					       PyCFunction_New(&meth[i], NULL));
> 		}
> 	}
> ...

Thank you, it works well.  Just one more question: Why isn't "mod"
Py_DECREFed again?

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus            ICQ 264-296-646



More information about the Python-list mailing list