This new version will replicate the directory structure of the original file and redirect the disassembled output to that file.
Code:
PyObject *disassemble(PyObject *obj)
{
static char buf[MAX_PATH], cmd[MAX_PATH<<1];
PyObject *dismod = NULL;
PyObject *disfunc = NULL;
PyObject *disresult = NULL;
PyCodeObject *co = (PyCodeObject *)obj;
char *filename = PyString_AsString(co->co_filename);
sprintf_s(buf,sizeof(buf),
"c:\\%s.dis",filename+3);
// make the slashes uniform
char *p = NULL;
p = strchr(buf,'/');
while(p != NULL )
{
*p = '\\';
p = strchr(p,'/');
}
// make sure the directory exists (by trying to creating it)
p = strchr(buf,'\\');
while( p != NULL )
{
*p = 0;
CreateDirectoryA(buf,NULL);
*p = '\\';
p = strchr(p+1,'\\');
}
// double up the slashes in the string
p = strchr(buf,'\\');
while(p != NULL )
{
memmove(p+1,p,sizeof(buf)-(p-buf-1));
p = strchr(p+2,'\\');
}
sprintf_s(cmd,sizeof(cmd),
"sys.stdout = open(\"%s\",'a')\n",buf);
PyRun_SimpleString("import sys\n");
PyRun_SimpleString(cmd);
dismod = PyImport_ImportModule("dis");
//printf("dismod: 0x%08X\n",dismod);
if( dismod != NULL )
{
Py_INCREF( dismod );
disfunc = PyObject_GetAttrString(dismod,"dis");
//printf("disfunc: 0x%08X\n",disfunc);
if( disfunc != NULL )
{
Py_INCREF( disfunc );
disresult = PyEval_CallFunction(disfunc,"(O)",obj);
}
}
PyRun_SimpleString("sys.stdout = sys.__stdout__\n");
Py_XDECREF( disresult );
Py_XDECREF( disfunc );
Py_XDECREF( dismod );
return disresult;
}