using the zipimporter module from my own C code?
Paul Miller
paul at fxtech.com
Wed Feb 11 15:44:01 EST 2004
>I'm starting to use the nifty 2.3 feature where modules can be bundled
>into .zip files. I'd like to bundle additional (text) data files in the
>same zip file, and load them in my C code.
By looking at zipimport.c and import.c in the Python code, I was able to
figure out how to get this to work. Here is the code, if anyone is interested:
// get the zipimport module
PyObject *zipimport = ::PyImport_ImportModule("zipimport");
if (zipimport)
{
// get the zipimporter type
PyObject *zipimporter =
::PyObject_GetAttrString(zipimport, "zipimporter");
if (zipimporter)
{
// here is the zip file path to open
std::string path = "full_path_to.zip";
// "call" the type to create a new zipimporter
instance, with the path
PyObject *importer =
::PyObject_CallFunction(zipimporter, "s", path.c_str());
if (importer)
{
// call the "get_data" method passing the
name of the file to retrieve
PyObject *data =
::PyObject_CallMethod(importer, "get_data", "s", file.c_str());
if (data)
{
// get the data as a string (this
assumes the file is TEXT)
const char *str =
::PyString_AsString(data);
if (str)
{
// do something with the data
}
Py_DECREF(data);
}
Py_DECREF(importer);
}
Py_DECREF(zipimporter);
}
Py_DECREF(zipimport);
}
More information about the Python-list
mailing list