469,282 Members | 1,701 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,282 developers. It's quick & easy.

Implementing class methods in C


I am having a problem implementing some methods of a python class in C.
The class is defined in python, but I would like to rewrite some methods
in c. Here is an example of what I want to do:

file _test.c:

#include <Python.h>

static PyObject *
func2(PyObject *self, PyObject *args)
{
if (self == NULL) {
PyErr_SetString(PyExc_SystemError, "self is NULL");
return NULL;
}

// Parse arguments
if (!PyArg_ParseTuple(args, ""))
{
return NULL;
}

Py_INCREF(Py_None);
return Py_None;
}

static PyMethodDef TestMethods[] = {
{"func2", func2, METH_VARARGS, "func2."},
{NULL, NULL, 0, NULL} /* Sentinel */
};

PyMODINIT_FUNC
init_test(void)
{
(void) Py_InitModule("_test", TestMethods);
}

----------------------------------------------------
test.py:

class Test:
def func1(self):
print "I am in func 1"

import _test
import new
Test.func2 = new.instancemethod(_test.func2, None, Test)
del(new)

t = Test()
t.func2()
When I run test.py, I get a SystemError exception (which is what I raise
if self is NULL). I think my confusion lies in the use of PyObject* self
in the function declaration. Shouldn't this be set to point to the
instance of class Test that I am calling it from? Am I misunderstanding
the purpose of PyObject* self? Thanks.

Naveen

---------------------------------------------------------------------
Naveen Michaud-Agrawal
Program in Molecular Biophysics
Johns Hopkins University
(410) 614 4435
Aug 15 '05 #1
0 1318

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Martyn Lawson | last post: by
1 post views Thread by nmichaud | last post: by
3 posts views Thread by Daniel Kraft | last post: by
8 posts views Thread by puzzlecracker | last post: by
21 posts views Thread by puzzlecracker | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.