Embedding Python - How to create a class instance

M

Miki Tebeka

Hello All,

I'm trying to embed Python in a C application.
What I didn't find is how to create an instance once I have a class object.

I'd like to do the equivalent of:

from a import A
obj = A()
obj.foo(10)

The following code omits error checking for clarity.
--- a.py ---
class A:
def foo(self, x):
print "A got %d" % x
--- a.py ---

--- a.c ---
int
main()
{
PyObject *module, *A, *dict, *a, *args;
PyObject *obj;

Py_Initialize();

PyRun_SimpleString("import sys; sys.path.append('.')");

module = PyImport_ImportModule("a");
dict = PyModule_GetDict(module);
A = PyDict_GetItemString(dict, "A");
/* FIXME: Create obj as instance of A (a = A()) */
obj = ???

foo = PyObject_GetAttrString(obj, "foo");
args = Py_BuildValue("(O, i)", obj, 49);
PyObject_CallObject(foo, args);

Py_Finalize();

return 0;
}
--- a.c ---

Thanks.
--
------------------------------------------------------------------------
Miki Tebeka <[email protected]>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.0 (Cygwin)

iD8DBQFCtR7x8jAdENsUuJsRAnkuAJ9g611ZSl7fWfAciiffUKzMvpmzNgCbB+B7
l7LRTVjusBuQ4PVA7tdN1R4=
=+p4K
-----END PGP SIGNATURE-----
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top