How to receive a FILE* from Python under MinGW?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Mar 23 00:33:29 EDT 2007


En Wed, 21 Mar 2007 03:35:09 -0300, John Pye <john.pye at gmail.com> escribió:

> Gabriel, if you think you can make an example that works, that would
> be great. I'm afraid I feel a bit out of my depth and don't have much
> confidence in this idea.

Try this. It's based on the example_nt extension module.

--- begin example.c ---
#include <io.h>
#include <fcntl.h>
#include <stdio.h>
#include <windows.h>
#include "Python.h"

static void externalfunction(FILE* f)
{
	// This is a "fake" external function that receives a FILE*
	printf("In externalfunction\n");
	fprintf(f, "Hello from externalfunction!\n");
}

static void wrapper(DWORD osfhandle)
{
	// This is a wrapper around externalfunction; receives an OS handle
	// for an open file, builds a FILE structure, and calls externalfunction
	FILETIME lw;
	SYSTEMTIME st;
	FILE* f;

	// This call is just to show that osfhandle is actually a Windows handle
	// as if one had used CreateFile(...) by example
	printf("Using osfhandle with GetFileTime\n");
	GetFileTime((HANDLE)osfhandle, NULL, NULL, &lw);
	FileTimeToSystemTime(&lw, &st);
	printf("LastWrite %d-%d-%d %02d:%02d:%02d.%03d\n", st.wYear, st.wMonth,  
st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

	// Now build a FILE struct from the received handle
	f = fdopen(_open_osfhandle(osfhandle,_O_APPEND),"a");
	externalfunction(f);
	fflush(f); // ensure all buffers are written
}

static PyObject *
filetest(PyObject *self, PyObject *args)
{
	DWORD handle;

	if (!PyArg_ParseTuple(args, "I", &handle))
		return NULL;
	printf("Received handle: %d\n", handle);
	wrapper(handle);
	printf("Done\n");
	Py_INCREF(Py_None);
	return Py_None;
}

static PyMethodDef example_methods[] = {
	{"filetest", filetest, 1, "filetest doc string"},
	{NULL, NULL}
};

void
initexample(void)
{
	Py_InitModule("example", example_methods);
}
--- end example.c ---

--- begin test.py ---
f = open("output.txt","w")
f.write("Hello from python!\n")
# ensure all buffers are written before calling the external function
f.flush()

import msvcrt
fh = msvcrt.get_osfhandle(f.fileno())
print "handle=",fh

import example
# calling example.filetest using the OS handle
example.filetest(fh)
f.close()

f = open("output.txt","r")
print "output.txt:"
print f.read()
f.close()
--- test.py ---

Build example.dll and rename it example.pyd; copy test.py to the same  
directory.
Running test.py gives:

C:\APPS\Python24\PYTHON~1.2\TEST_M~1\Release>python24 test.py
handle= 1988
Received handle: 1988
Using osfhandle with GetFileTime
LastWrite 2007-3-23 04:25:08.000
In externalfunction
Done
output.txt:
Hello from python!
Hello from externalfunction!

-- 
Gabriel Genellina




More information about the Python-list mailing list