Embedding Python - How to create a class instance
Miki Tebeka
miki.tebeka at zoran.com
Sun Jun 19 03:29:53 EDT 2005
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 <miki.tebeka at zoran.com>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 193 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050619/5b3f338e/attachment.sig>
More information about the Python-list
mailing list