Embedding Python - How to create a class instance
Denis S. Otkidach
ods at strana.ru
Mon Jun 20 03:53:23 EDT 2005
On Sun, 19 Jun 2005 10:29:53 +0300
Miki Tebeka <miki.tebeka at zoran.com> wrote:
> 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.
Class is a callable object. Just call it to create instance.
> 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 = ???
obj = PyObject_CallObject(A, NULL);
>
> foo = PyObject_GetAttrString(obj, "foo");
> args = Py_BuildValue("(O, i)", obj, 49);
> PyObject_CallObject(foo, args);
PyObject_CallMethod(obj, "foo", "i", 49);
> Py_Finalize();
>
> return 0;
> }
> --- a.c ---
--
Denis S. Otkidach
http://www.python.ru/ [ru]
More information about the Python-list
mailing list