Extending embedded Python: Adding single methods

Thomas Heller theller at python.net
Thu Mar 9 08:24:15 CET 2006


Torsten Bronger wrote:
> 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?

A mistake, as it seems.

Thomas




More information about the Python-list mailing list