473,757 Members | 5,404 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reading a python file object in c extension crashes python

Hi,

I have an extension in which a file object is created in python and
passed down to a c extension which attempts to read from it or write
to it. Writing to the file pointer seems to work okay, but reading
from it results in EBADF. It also causes python to crash on exit.

I've attached the minimal (I think) c code, python code, build script,
build log, and run log. Any and all help is greatly appreciated.

Thanks.

System: Win-XP Professional
Compiler: Vc7 (MSVS 2003)
Python: Python 2.4.1
Builder: SCons 0.96.1

P.S. Sorry for including everything in one message. I keep getting
bounced when I attach them.
### file:my_module. c -------------------------------------------------

#include <Python.h>
#define MAXLEN 128

int
my_read(char *buffer, int max, FILE *fp)
{
int n = 0;
fprintf (stdout, "[c] pre-read: errno=%d, fp=%x\n", errno, fp);
n = fread(buffer, 1, max, fp);
fprintf (stdout, "[c] post-write: errno=%d, fp=%x, count=%d,
data='%s'\n", errno, fp, n, buffer);
return n;
}

int
my_write(const char *buffer, FILE *fp)
{
int n = 0;
fprintf (stdout, "[c] pre-write: errno=%d, fp=%x, data='%s'\n",
errno, fp, buffer);
n = fprintf(fp, "%s", buffer);
fprintf (stdout, "[c] post-write: errno=%d, fp=%x, count=%d\n",
errno, fp, n);
return n;
}

static PyObject *
my_module_my_re ad(PyObject *self, PyObject *args)
{
char buffer[MAXLEN];
int count = 0;
FILE *fp = NULL;
PyObject* py_file = NULL;

memset((void*)& (buffer),0,size of(char)*MAXLEN );

if (!PyArg_ParseTu ple(args, "O", &py_file))
return NULL;

if (PyFile_Check(p y_file))
{

count = my_read((char*) &(buffer), MAXLEN, PyFile_AsFile(p y_file));
return Py_BuildValue(" (is)", count, (char*)buffer);
}
return NULL;
}

static PyObject *
my_module_my_wr ite(PyObject *self, PyObject *args)
{
char buffer[MAXLEN];
int count = 0;
FILE *fp = NULL;
PyObject* py_file = NULL;
const char* py_string;

memset((void*)& (buffer),0,size of(char)*MAXLEN );

if (!PyArg_ParseTu ple(args, "sO", &py_string, &py_file))
return NULL;

if ((PyFile_Check( py_file)) && (py_string != NULL))
{
count = my_write(py_str ing, PyFile_AsFile(p y_file));
return Py_BuildValue(" i", count);
}
return NULL;
}

static PyMethodDef MyModuleMethods[] = {
{"my_read", my_module_my_re ad, METH_VARARGS,
"read at most 128 bytes from a file"},
{"my_write", my_module_my_wr ite, METH_VARARGS,
"write a string to a file"},
{NULL,NULL,0,NU LL}
};

PyMODINIT_FUNC
initmy_module(v oid)
{
PyObject *m;
m = Py_InitModule(" my_module", MyModuleMethods );
}
### file: my_module.py ------------------------------------------------

import my_module

filename = "hello.txt"
fp1 = open(filename, "wb")
print "[py] pre-write: fp=%s" % (fp1)
result1 = my_module.my_wr ite("Hello, World!", fp1)
print "[py] result=", result1
fp1.close()

fp2 = open(filename, "rb")
print "[py] pre-read: fp=%s" % (fp2)
result2 = my_module.my_re ad(fp2)
print "[py] result=", result2
#fp2.close()
# crashes python here EBADF when fp2.close() is called
print "done"
# crashes python here when fp2.close() is commented out

### file: Sconstruct --------------------------------------------------
env = Environment()
import os

python_include_ path = os.path.join(os .path.sep,'Pyth on24','include' )
python_lib_path = os.path.join(os .path.sep,'Pyth on24','libs')
python_libs = 'python24'
my_module_name = 'my_module'
my_module_sourc es = 'my_module.c'

library = env.SharedLibra ry(my_module_na me,
my_module_sourc es,
CPPPATH=[python_include_ path],
LIBPATH=[python_lib_path],
LIBS=[python_libs])
### file: build.log ---------------------------------------------------
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
cl /nologo /I\Python24\incl ude /c my_module.c /Fomy_module.obj
my_module.c
link /nologo /dll /out:my_module.d ll /implib:my_modul e.lib
/LIBPATH:\Python 24\libs python24.lib my_module.obj
Creating library my_module.lib and object my_module.exp
scons: done building targets.
### file: run.log -----------------------------------------------------
[py] pre-write: fp=<open file 'hello.txt', mode 'wb' at 0x009B54A0>
[c] pre-write: errno=0, fp=7c38b548, data='Hello, World!'
[c] post-write: errno=0, fp=7c38b548, count=13
[py] result= 13
[py] pre-read: fp=<open file 'hello.txt', mode 'rb' at 0x009B5608>
[c] pre-read: errno=0, fp=7c38b548
[c] post-write: errno=9, fp=7c38b548, count=0, data=''
[py] result= (0, '')
done
Jul 19 '05 #1
0 1923

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1983
by: youngdubliner | last post by:
I'm having a problem ........ I've stripped all my code to help isolate the problem. Its seems to be with importing numarray when python is embedded in C. I have a simple C program it Opens Python imports a script and then Closes Python like so .......
3
3782
by: Matthias Baas | last post by:
Hi, are there any guidelines about what to do if a Windows extension for Python 2.4 requires the C++ runtime (msvcp71.dll)? If I want to distribute a binary installer of an extension that contains C++ code, should I really include the msvcp71.dll in the package? It doesn't sound like a good idea to me if every package places another copy of this dll somewhere in the Python directory. Python 2.4 does install the C runtime (msvcr71.dll)...
13
3975
by: mloichate | last post by:
I must read a very heavy-weight text plain file (usually .txt extension) )and replace a given character with another given character in all text inside the file. My application was working pretty well with this below shown code (code placed in a buttonclick event after selecting the file in a normal OpenFileDialog): --------------------------------- System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\1.txt"); string all =...
8
2428
by: Brennus | last post by:
I have a dll/so which embeds python. I can verify it works by compiling it as an executable and adding an appropriate main. I tried to write unit tests for this library with ctypes and a simple python script. Access violations and other strange things result. I suspect this is because I am basically embedding python in python at this point. How can I make my dll/so with embedded python support use via ctypes?
2
2294
by: robert | last post by:
When employing complex UI libs (wx, win32ui, ..) and other extension libs, nice "only Python stack traces" remain a myth. Currently I'm hunting again a rare C-level crash bug of a Python based Windows app with rare user reports - and still in the dark (I get snippets of machine stack traces / screenshots with random "mem. access error" / "python caused the runtime to terminate in an unusual way" / ..) I'd like to hook a kind of quality...
0
4582
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 349 open ( +7) / 3737 closed (+25) / 4086 total (+32) Bugs : 939 open (-12) / 6648 closed (+60) / 7587 total (+48) RFE : 249 open ( -8) / 278 closed (+12) / 527 total ( +4) New / Reopened Patches ______________________
2
2334
by: oyster | last post by:
For the word "Pure", I mean it is not a C/C++/Z++.. extension, so that we can use it under pythons of different version. Is it possible? I don't like to update the module for different python and the module Currently, I am writing the interface to iup(http://www.tecgraf.puc-rio.br/iup) via ctypes, but find 2 too strange things which have let me feel blue for some days, and I don't know whether it can be successful or not. Can anyone...
0
9487
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9884
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9735
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8736
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7285
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5168
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5324
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3828
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.