473,804 Members | 2,296 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C-API: A beginner's problem

I recently started learning C since I want to be able to write Python
extension modules. In fact, there is no need for it, but I simply want
to try something new ...

I tried to implement the bubblesort algorithm in C and to use it in
python; bubblesort.c compiles fine, but whenever I want to import the
modul and call the function I get a segmentation fault. This is what the
code looks like:

static PyObject *py_bubblesort( PyObject *self, PyObject *args) {
PyObject *seq = NULL, *item, *newseq = NULL;
int seqlen, i;

if(!PyArg_Parse Tuple(args, "O", &seq)) {
return NULL;
}
seq = PySequence_Fast (seq, "argument must be iterable");
if(!seq) {
return NULL;
}
seqlen = PySequence_Fast _GET_SIZE(seq);
int list[seqlen];
for (i = 0; i <= seqlen; i++) {
item = PySequence_Fast _GET_ITEM(seq, i);
list[i] = item;
}
bubblesort(list , seqlen);
newseq = PyList_New(seql en);
if(!newseq) {
return NULL;
}
for(i = 0; i < seqlen; i++) {
PyList_SetItem( newseq, i, list[i]);
}

return newseq;

bubblesort(int list[], int seqlen) is doing the actual job and it is
working.

What did I do wrong? As I am quite new to C, I probably made many
mistakes, so please feel free to correct me.

Cheers,
Fabian
Mar 19 '06 #1
10 1505
Fabian Steiner wrote:
What did I do wrong? As I am quite new to C, I probably made many
mistakes, so please feel free to correct me.
The following line:
for (i = 0; i <= seqlen; i++) {


Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last
assignment will be out of bounds and probably corrupts heap.
Mar 19 '06 #2
Heikki Salo wrote:
Fabian Steiner wrote:
What did I do wrong? As I am quite new to C, I probably made many
mistakes, so please feel free to correct me.


The following line:
> for (i = 0; i <= seqlen; i++) {


Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last
assignment will be out of bounds and probably corrupts heap.


And closer look tells that the code should not even compile. Is the code
cut & pasted directly? Line "list[i] = item;" tries to assign a pointer
to an int-array, which should not compile. There are other similar oddities.
Mar 19 '06 #3
Heikki Salo wrote:

And closer look tells that the code should not even compile. Is the
code cut & pasted directly? Line "list[i] = item;" tries to assign a
pointer to an int-array, which should not compile. There are other
similar oddities.


.... such as the declaration of list at a point in the code which is not
permitted in C, and using a non constant value for the length (which is
also not allowed).
Mar 19 '06 #4
Duncan Booth wrote:
Heikki Salo wrote:

And closer look tells that the code should not even compile. Is the
code cut & pasted directly? Line "list[i] = item;" tries to assign a
pointer to an int-array, which should not compile. There are other
similar oddities.


... such as the declaration of list at a point in the code which is not
permitted in C, and using a non constant value for the length (which is
also not allowed).


They are allowed in C99, according to GCC's manual.

Mar 19 '06 #5
Nick Smallbone wrote:
Duncan Booth wrote:
Heikki Salo wrote:
>
> And closer look tells that the code should not even compile. Is the
> code cut & pasted directly? Line "list[i] = item;" tries to assign a
> pointer to an int-array, which should not compile. There are other
> similar oddities.


... such as the declaration of list at a point in the code which is not
permitted in C, and using a non constant value for the length (which is
also not allowed).


They are allowed in C99, according to GCC's manual.


Which just shows how long it is since I wrote any C.
Mar 19 '06 #6
Heikki Salo wrote:
Heikki Salo wrote:
Fabian Steiner wrote:
What did I do wrong? As I am quite new to C, I probably made many
mistakes, so please feel free to correct me.


The following line:
> for (i = 0; i <= seqlen; i++) {


Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last
assignment will be out of bounds and probably corrupts heap.


And closer look tells that the code should not even compile. Is the code
cut & pasted directly? Line "list[i] = item;" tries to assign a pointer
to an int-array, which should not compile. There are other similar
oddities.


Okay, thank you (and the others) for these hints. As you see, I am quite
new to C and I just wrote these lines by using parts I have found in the
newsgroup. Unfortunately, the Python C-API documentation / tutorial
won't help me since it is quite difficult to understand because of the
lack of basics.

What do I have to change in order to make the code work?

Thank you very much in advance!

Cheers,
Fabian
Mar 19 '06 #7
Fabian Steiner wrote:
I recently started learning C since I want to be able to write Python
extension modules. In fact, there is no need for it, but I simply want
to try something new ...

I tried to implement the bubblesort algorithm in C and to use it in
python; bubblesort.c compiles fine, but whenever I want to import the
modul and call the function I get a segmentation fault. This is what the
code looks like:

static PyObject *py_bubblesort( PyObject *self, PyObject *args) {
PyObject *seq = NULL, *item, *newseq = NULL;
int seqlen, i;
long it;
if(!PyArg_Parse Tuple(args, "O", &seq)) {
return NULL;
}
seq = PySequence_Fast (seq, "argument must be iterable");
if(!seq) {
return NULL;
}
seqlen = PySequence_Fast _GET_SIZE(seq);
int list[seqlen];
for (i = 0; i <= seqlen; i++) {
That is one iteration too much. Use

for (i = 0; i < seglen; i++)
item = PySequence_Fast _GET_ITEM(seq, i);
Now item is a PyObject*. You'll have to convert it to an integer now:

it = PyInt_AsLong(it em);
if (it == -1 && PyErr_Occurred( )) {
Py_DECREF(seq);
/* set a new exception here if you like */
return NULL;
}
list[i] = it;
}
bubblesort(list , seqlen);
newseq = PyList_New(seql en);
if(!newseq) {
Do not forget to DECREF seq:
Py_DECREF(seq);
return NULL;
}
for(i = 0; i < seqlen; i++) {
PyList_SetItem( newseq, i, list[i]);
List items must be PyObject*s, not plain ints. Use:
PyList_SetItem( newseq, i, PyInt_FromLong( list[i]));
(This is sloppy error checking, but if PyInt_FromLong fails you're out of
memory anyways ;)
}
Again, seq is not needed anymore:
Py_DECREF(seq);
return newseq;

bubblesort(int list[], int seqlen) is doing the actual job and it is
working.

What did I do wrong? As I am quite new to C, I probably made many
mistakes, so please feel free to correct me.


There's quite a bit you can overlook, especially stale references to PyObjects.
I'm not even sure the code compiles or runs correctly with my corrections ;)

Cheers,
Georg
Mar 19 '06 #8
Georg Brandl wrote:
Fabian Steiner wrote:
[...]
for (i = 0; i <= seqlen; i++) {
That is one iteration too much. Use

for (i = 0; i < seglen; i++)
item = PySequence_Fast _GET_ITEM(seq, i);


Now item is a PyObject*. You'll have to convert it to an integer now:

it = PyInt_AsLong(it em);


Why do you use PyInt_AsLong() here? As the documentation says it returns
a long type: long PyInt_AsLong(Py Object *io)
On the other hand I can't find anything like PyInt_AsInt().
if (it == -1 && PyErr_Occurred( )) {
Py_DECREF(seq);
Why is this Py_DECREF() needed? What does it do exactly? When do I have
to call this function? Obviously, there is also Py_INCREF(). When do you
need this function?
[...]
There's quite a bit you can overlook, especially stale references to PyObjects.
I'm not even sure the code compiles or runs correctly with my corrections ;)


Now, it compiles fine, without any warnings and using it in Python works
either :-) Now I have to try to understand what the different parts are
doing and why they are necessary.

Thank you very much so far!

Cheers,
Fabian
Mar 20 '06 #9
Fabian Steiner wrote:
Georg Brandl wrote:
Fabian Steiner wrote:
[...]
for (i = 0; i <= seqlen; i++) {


That is one iteration too much. Use

for (i = 0; i < seglen; i++)
item = PySequence_Fast _GET_ITEM(seq, i);


Now item is a PyObject*. You'll have to convert it to an integer now:

it = PyInt_AsLong(it em);


Why do you use PyInt_AsLong() here? As the documentation says it returns
a long type: long PyInt_AsLong(Py Object *io)
On the other hand I can't find anything like PyInt_AsInt().


Python's int objects carry a long, so they can return you this long.
On most 32-bit platforms, int == long anyway, but for 64-bit you'd have
to declare list as long too.
if (it == -1 && PyErr_Occurred( )) {
Py_DECREF(seq);


Why is this Py_DECREF() needed? What does it do exactly? When do I have
to call this function? Obviously, there is also Py_INCREF(). When do you
need this function?


This is for reference counting. Since you created seq with PySequence_Fast
you "own" a reference to it (it has reference count 1). Since nothing else
references that sequence, it has to be deallocated before the function exits.
You use Py_DECREF to decrease the reference count to 0, thus telling Python
that it's safe to free the memory associated with it.

Most API functions that return a PyObject increase its reference count by 1,
leaving you in charge to do something with this ("your") reference.

Other examples of how references can be juggled with:

item = PySequence_Fast _GET_ITEM(seq, i);

PySequence_Fast _GET_ITEM does return a PyObject, but it doesn't increase the
reference count, so you don't have to DECREF item anywhere. However, if you were
to store item in a structure of some sort, you'd have to INCREF it so that
Python doesn't destroy it while it's still referenced by your structure.

PyList_SetItem( newseq, i, PyInt_FromLong( list[i]));

PyInt_FromLong( ) returns a new PyObject with one reference, but PyList_SetItem
"steals" that reference from you (it stores the PyObject in a structure without
increasing its reference count). Therefore, you don't own a reference to the
integer object anymore and don't have to DECREF it.

newseq = PyList_New(seql en);
(...)
return newseq;

Here, you own a reference to newseq, but you return the object, so you have to
keep it alive. Thus, no DECREF.
[...]
There's quite a bit you can overlook, especially stale references to PyObjects.
I'm not even sure the code compiles or runs correctly with my corrections ;)


Now, it compiles fine, without any warnings and using it in Python works
either :-) Now I have to try to understand what the different parts are
doing and why they are necessary.


Cheers,
Georg
Mar 20 '06 #10

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

Similar topics

5
2167
by: Rolf Wester | last post by:
Hi, I'm just beginning PHP programming. I have installed Apache 2.0.48 and PHP 4.3.3. The installation went well. Then I was trying a little example. HTML page: <html> <head> <title>test</title>
1
2381
by: Doobai | last post by:
Hi, hope you can help, Just starting to learn about objects-relationals and I've come across what I hope is a little problem, when I try and make the method code, I get told the type already exists, heres a stripped down example, I'm sure its a terribly simple mistake: -- Example object type : CREATE OR REPLACE TYPE student_type as object
6
2198
by: Fredrik Nelson | last post by:
Hi, I have used xsl to transform xml from sqlserver in and it works fine now i have a webservice that uses a dataset to get the data and return it as xml like the code below <WebMethod()> _ Public Function ReturnEarnedValues() As XmlDocument Dim MyStream As New IO.StringWriter Dim XD As New XmlDocument
2
2297
by: trond | last post by:
Hello all, I am building a personal web site in VS2005 as a kind of learing project for myself, so forgive me if this is a novice question. I am planning to use an XML file called SiteSettings.xml to hold site-wide info such as copyright info, site title (e.g. my homepage) etc. Currently this xml file looks like this: <?xml version="1.0"?> <SiteSettings>
7
1607
by: mabond | last post by:
Hi Can't get my head round something which I reckon should be simple. My app has a main form (frmMain). MdiContainer set to true. A menu item triggers a new form (frmSelect) whose parent is frmMain Button on frmSelect triggers a new form (frmReport) whose parent also needs to be frmMain When frmReport loads and displays I don't want user to see frmSelect, but I
4
8651
by: Zahpod | last post by:
Hi all The Code: #include <stdio.h> #include <sys/ddi.h> main(int argc, char *argv) { int i,dec; if ( argc < 2 )
6
1510
by: Lars | last post by:
Hi all If this is the wrong list for beginners trouble I apologize. please refer to me the correct list in such case. I am trying to create a simple linked list but I keep getting segmentation errors and I dont know why. I realize that I do not free the allocated memory but the segfault happpens (it seems) with the insert function. Can any one explain ? Regards Lars
6
1575
by: Ivan Reborin | last post by:
Hello all, I'm new to python, new as newbies get, so please, don't take wrongly if this seems like a stupid or overly simple question. I'm going through examples in a book I have ("Beginning python", by Hetland Marcus) and I just started doing wxPython examples. But every sample I try, for example:
0
9714
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
10599
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10347
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
9173
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
7635
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
5531
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...
1
4308
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
2
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.