calling a class method in a python module

R

rtuhin

Hi

I am trying to write a C code to call a class function in a python
module. Here's my python module:

def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b

def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

class MyClass:
"A simple example class"
i = 12345
def f(self):
return 'hello world'


Can anybody tell me how to call "f" in my C code?

Thanks,
Tuhin
 
F

Farshid Lashkari

Can anybody tell me how to call "f" in my C code?

Assuming you already have a handle to an instance of MyClass this should
do the trick:

PyObject *func = PyObject_GetAttrString(MyClassInst,"f");
if(func) {
PyObject *result = PyObject_CallObject(func,NULL);
if(result) {
//Do something with result
Py_DECREF(result);
}
Py_DECREF(func);
}

Have a look in the "Python/C API Reference Manual" for more information.

-Farshid
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top