From zouxianjun at huawei.com Mon Jan 5 08:08:13 2009 From: zouxianjun at huawei.com (zouxianjun 45728) Date: Mon, 05 Jan 2009 15:08:13 +0800 Subject: [capi-sig] Some problem when i use Python C/API to embed python script, need Help...... Message-ID: when the program run as exe, everything goes right, but if i compile the program as a .so lib, use other program to load the .so lib and run, it goes wrong,in the lib i also use PyRun_SimpleString("import base64"); it goes wrong.....my python version is 2.3, i want to know what's the problem...... PyErr_Print() print the error info below: Traceback (most recent call last): File "./myModule111.py", line 3, in ? import base64 File "/usr/lib/python2.3/base64.py", line 7, in ? import binascii ImportError: /usr/lib/python2.3/lib-dynload/binascii.so: undefined symbol: PyExc_TypeError i check the binascii.so, ldd -r binascii.so, this lib really has many undefined symbols include PyExc_TypeError, but the problem is when the program is executable, it can goes fine...... when i compile the program as .so lib, i add -Xlinker -export-dynamic, it doesn't solve the problem......... ****************************************************************************************** This email and its attachments contain confidential information from HUAWEI, which is intended only for the person or entity whose address is listed above. Any use of the information contained here in any way (including, but not limited to, total or partial disclosure, reproduction, or dissemination) by persons other than the intended recipient(s) is prohibited. If you receive this email in error, please notify the sender by phone or email immediately and delete it! ***************************************************************************************** From Jack.Jansen at cwi.nl Tue Jan 6 21:58:10 2009 From: Jack.Jansen at cwi.nl (Jack Jansen) Date: Tue, 6 Jan 2009 21:58:10 +0100 Subject: [capi-sig] Some problem when i use Python C/API to embed python script, need Help...... In-Reply-To: References: Message-ID: <00E98DDD-138F-4AFB-B39A-5AB30D15025E@cwi.nl> On 5-Jan-2009, at 08:08 , zouxianjun 45728 wrote: > when the program run as exe, everything goes right, but if i compile > the program as a .so lib, use other program to load the .so lib and > run, it goes wrong,in the lib i also use PyRun_SimpleString("import > base64"); it goes wrong.....my python version is 2.3, i want to know > what's the problem...... PyErr_Print() print the error info > below: > Traceback (most recent call last): > File "./myModule111.py", line 3, in ? > import base64 > File "/usr/lib/python2.3/base64.py", line 7, in ? > import binascii > ImportError: /usr/lib/python2.3/lib-dynload/binascii.so: undefined > symbol: PyExc_TypeError > > i check the binascii.so, ldd -r binascii.so, this lib really has > many undefined symbols include PyExc_TypeError, but the problem is > when the program is executable, it can goes fine...... > > when i compile the program as .so lib, i add -Xlinker -export- > dynamic, it doesn't solve the problem......... Ah, the joys of dynamic linkers... You'll need to specify the exact version of your operating system (probably Linux, but maybe MacOSX or some other unix variant?), and, for completeness, your compiler and linker version. Sometimes symbols in the base executable are available to all dynamically loaded modules, but symbols in modules that are themselves loaded dynamically not. This seems to be what's biting you. Oh yes: can you try a newer version of Python? I fixed a similar error for Python on MacOSX at some point in the past, it could be that you're looking at an error has been fixed in the mean time, 2.3 is pretty old by now. -- Jack Jansen, , http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From ideasman42 at gmail.com Thu Jan 15 05:57:49 2009 From: ideasman42 at gmail.com (Campbell Barton) Date: Wed, 14 Jan 2009 20:57:49 -0800 Subject: [capi-sig] Getting full traceback text Message-ID: <7c1ab96d0901142057k6d9a3440p18b6307d3fac51df@mail.gmail.com> recently I have been experimenting with a new api for blender3d, one of the things it needs to be able to do is give python errors (tracebacks) to our own error reporting api. The problem is that Python/C api has no way to get the text that PyErr_Print() prints, as a string. This seems not such an unusual thing for an api to require, after all, many applications dont run with a console to display text. So far I think there are 3 ways to do this. * Create a pipe, open it with fdopen(), then temporarily replace stderr and stdout and call PyErr_Print().... then get the text from that pipe. I havnt tried this yet and I'm not sure if its a good cross platform solution. * Copy and paste Pythons C traceback function into my own function that builds a string rather then printing it. This really isnt an attractive option. * Use pythons traceback module from C (this isnt so bad, but Id prefer not to have core parts of our api relying on *.py modules) Is there some other way to do this? or is anyone currently doing this in their application? Here is the Python 3.x C api code for getting the traceback. -------------------- snip static void pyop_error_report(ReportList *reports) { /* # in python this would be... import traceback string = ' '.join(traceback.format_exc()) */ PyObject *type, *value, *traceback; PyObject *mod; PyObject *ret, *list, *string, *args; /* Save the current exception */ PyErr_Fetch(&type, &value, &traceback); mod = PyImport_ImportModule("traceback"); if (!mod) { /* print some error */ return; } list= PyObject_CallMethod(mod, "format_exception", "OOO", type, value, traceback); string= PyUnicode_FromString("\n"); ret= PyUnicode_Join(string, list); Py_DECREF(list); Py_DECREF(string); BKE_report(reports, RPT_ERROR, _PyUnicode_AsString(ret)); Py_DECREF(ret); PyErr_Clear(); } -------------------- -- - Campbell From python_capi at behnel.de Thu Jan 15 09:26:56 2009 From: python_capi at behnel.de (Stefan Behnel) Date: Thu, 15 Jan 2009 09:26:56 +0100 (CET) Subject: [capi-sig] Getting full traceback text In-Reply-To: <7c1ab96d0901142057k6d9a3440p18b6307d3fac51df@mail.gmail.com> References: <7c1ab96d0901142057k6d9a3440p18b6307d3fac51df@mail.gmail.com> Message-ID: <47100.213.61.181.86.1232008016.squirrel@groupware.dvs.informatik.tu-darmstadt.de> Campbell Barton wrote: > recently I have been experimenting with a new api for blender3d, one > of the things it needs to be able to do is give python errors > (tracebacks) to our own error reporting api. > > The problem is that Python/C api has no way to get the text that > PyErr_Print() prints, as a string. > [...] > * Use pythons traceback module from C (this isnt so bad, but Id prefer > not to have core parts of our api relying on *.py modules) I'd opt for not fixing problems before they clearly turn out to be problems, and just go with the traceback module. You only use it for debugging the unexpected failure case after all, so this isn't performance critical or anything. Stefan From paddy at earth.li Fri Jan 16 12:00:10 2009 From: paddy at earth.li (Patrick Moore) Date: Fri, 16 Jan 2009 11:00:10 +0000 Subject: [capi-sig] Compiling for multiple versions of libpython2 Message-ID: <20090116110010.GQ30448@the.earth.li> Hi all, Currently we have a python/c hybrid which works well and compiles against 2.3 and up nicely, and runs sensibly against all of these, however we still need to compile directly against the correct python library before distribution. The question is, do any of you know a sensible way of compiling and opening the python libraries such that, so long as the end user has at least python2.3 libs (and compatible apis), that it will automagically just run. This is primarily to avoid end users having multiple versions of python on there systems, and to aid us with only having to build and test one exectuable. All suggestions greatly welcomed as we're struggling to find an elegant solution to this. cheers, paddy -- ----------( I am an idiot )---------- paddy ----( )---- yddap Htag.pl 0.0.23 From philipp at achtziger.de Fri Jan 16 17:34:54 2009 From: philipp at achtziger.de (Philipp Heuser) Date: Fri, 16 Jan 2009 17:34:54 +0100 Subject: [capi-sig] Py_BuildValue, Array from C to Python Message-ID: <4970B72E.7050603@achtziger.de> Hi all, I am trying to return an array from C to Python. Since it is of variable size, return Py_BuildValue("[f,f,f]", array[0], array[1], array[2]); does not help. How do I do that? Any help is appreciated, kind regards Philipp From ggpolo at gmail.com Fri Jan 16 18:31:51 2009 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 16 Jan 2009 15:31:51 -0200 Subject: [capi-sig] Py_BuildValue, Array from C to Python In-Reply-To: <4970B72E.7050603@achtziger.de> References: <4970B72E.7050603@achtziger.de> Message-ID: On Fri, Jan 16, 2009 at 2:34 PM, Philipp Heuser wrote: > Hi all, > > I am trying to return an array from C to Python. Since it is of variable > size, > > return Py_BuildValue("[f,f,f]", array[0], array[1], array[2]); > > does not help. How do I do that? > Create an empty list (PyList_New(0)) and then append (PyList_Append) items (PyFloat_FromDouble) as you loop over this array variable. I'm considering for some reason you don't know the size of this variable, so it has a sentinel in the end, but if it is not the case you can create a list with its final size and then use PyList_SetItem. > Any help is appreciated, > kind regards > Philipp -- -- Guilherme H. Polo Goncalves From jon at indelible.org Fri Jan 16 18:41:37 2009 From: jon at indelible.org (Jon Parise) Date: Fri, 16 Jan 2009 09:41:37 -0800 Subject: [capi-sig] Py_BuildValue, Array from C to Python In-Reply-To: <4970B72E.7050603@achtziger.de> References: <4970B72E.7050603@achtziger.de> Message-ID: <1aff89d70901160941h3f1c8ae5y416a335b4f37d0eb@mail.gmail.com> On Fri, Jan 16, 2009 at 8:34 AM, Philipp Heuser wrote: > I am trying to return an array from C to Python. Since it is of variable > size, > > return Py_BuildValue("[f,f,f]", array[0], array[1], array[2]); > > does not help. How do I do that? Try creating a Python tuple or list in your C function and returning that object instead. You can read about those C API functions here: http://docs.python.org/c-api/tuple.html http://docs.python.org/c-api/list.html -- Jon Parise (jon of indelible.org) :: "Scientia potentia est" From marcglec at free.fr Sun Jan 18 01:06:31 2009 From: marcglec at free.fr (Marc) Date: Sun, 18 Jan 2009 01:06:31 +0100 Subject: [capi-sig] How to manipulate C table as python list ? Message-ID: <1232237191.7347.18.camel@gondor> Hi, I would like to use a C program which manipulates table as a python module acting on a list. My C code is the following: int sum(int *tab, int n) { int i, s = 0; for (i=0; i 6 print my_module.sum(b) -> 30 My question is: which option should I use with PyArg_ParseTuple? I'm totaly lost with all its option (O, O&, O!, etc) Thx, Marc. From hniksic at xemacs.org Sun Jan 18 09:51:38 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 18 Jan 2009 09:51:38 +0100 Subject: [capi-sig] How to manipulate C table as python list ? In-Reply-To: <1232237191.7347.18.camel@gondor> (Marc's message of "Sun\, 18 Jan 2009 01\:06\:31 +0100") References: <1232237191.7347.18.camel@gondor> Message-ID: <87eiz1f145.fsf@mulj.homelinux.net> Marc writes: > I would like to use a C program which manipulates table > as a python module acting on a list. > My C code is the following: > int sum(int *tab, int n) > { > int i, s = 0; > > for (i=0; i { > s += tab[i]; > } > > return s; > } > Now, I would like to use it as a python module > where tab would be a python list. > I read some examples in the documentation but > the size of the list is always assumed to be known > such that one can use PyArg_ParseTuple > with a format description for each argument. In this case you only use PyArg_ParseTuple to get to the object that represents the list. In fact, since you only need one argument, you don't need PyArg_ParseTuple at all, simply declare your function to take one argument using the METH_O in the function description, and code it like this: PyObject *sum(PyObject *ignored, PyObject *lst) { int i, s = 0; if (!PyList_Check(lst)) { PyErr_Format(PyExc_TypeError, "sum: expected list, got %s", lst->ob_type->tp_name); return NULL; } for (i = 0; i < PyList_GET_SIZE(lst); i++) { ... sum the list ... return PyInt_FromLong(s); } > My question is: > which option should I use with PyArg_ParseTuple? If your function is declared to take one argument with METH_O, you don't need PyArg_ParseTuple at all. If it's declared to take a variable number of arguments, you'd use it like this: PyObject *sum(PyObject *ignored, PyObject *args) { int i, s = 0; PyObject *lst; if (!PyArg_ParseTuple(args, "O", &lst)) return NULL; ... } From hniksic at xemacs.org Sun Jan 18 09:56:05 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 18 Jan 2009 09:56:05 +0100 Subject: [capi-sig] Py_BuildValue, Array from C to Python In-Reply-To: <4970B72E.7050603@achtziger.de> (Philipp Heuser's message of "Fri\, 16 Jan 2009 17\:34\:54 +0100") References: <4970B72E.7050603@achtziger.de> Message-ID: <87ab9pf0wq.fsf@mulj.homelinux.net> Philipp Heuser writes: > I am trying to return an array from C to Python. Since it is of > variable size, > > return Py_BuildValue("[f,f,f]", array[0], array[1], array[2]); > > does not help. How do I do that? You can do it like you'd do it in Python: get an empty list, append array elements to it in a loop, and return the resulting list when you're done. Since you're coding it in C, it might make sense to attempt to be a bit more efficient and preallocate the list to exactly the needed size. PyObject *lst = PyList_New(array_len); if (!lst) return NULL; for (i = 0; i < array_len; i++) { PyObject *num = PyFloat_FromDouble(array[i]); if (!num) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, num); // reference to num stolen } return lst; From python_capi at behnel.de Sun Jan 18 17:18:41 2009 From: python_capi at behnel.de (Stefan Behnel) Date: Sun, 18 Jan 2009 17:18:41 +0100 Subject: [capi-sig] How to manipulate C table as python list ? In-Reply-To: <87eiz1f145.fsf@mulj.homelinux.net> References: <1232237191.7347.18.camel@gondor> <87eiz1f145.fsf@mulj.homelinux.net> Message-ID: <49735661.8080707@behnel.de> Hrvoje Niksic wrote: > PyObject *sum(PyObject *ignored, PyObject *lst) > { > int i, s = 0; > if (!PyList_Check(lst)) { > PyErr_Format(PyExc_TypeError, "sum: expected list, got %s", > lst->ob_type->tp_name); > return NULL; > } > for (i = 0; i < PyList_GET_SIZE(lst); i++) { > ... sum the list ... > return PyInt_FromLong(s); > } > >> My question is: >> which option should I use with PyArg_ParseTuple? > > If your function is declared to take one argument with METH_O, you > don't need PyArg_ParseTuple at all. If it's declared to take a > variable number of arguments, you'd use it like this: > > PyObject *sum(PyObject *ignored, PyObject *args) > { > int i, s = 0; > PyObject *lst; > if (!PyArg_ParseTuple(args, "O", &lst)) > return NULL; > ... > } You can also write your code in Cython. The following Cython code will generate roughly the same C code that you present above: def sum(list l): cdef int i, s = 0 for i in l: s += i return s http://cython.org/ Stefan From Jack.Jansen at cwi.nl Sun Jan 18 23:24:43 2009 From: Jack.Jansen at cwi.nl (Jack Jansen) Date: Sun, 18 Jan 2009 23:24:43 +0100 Subject: [capi-sig] How to manipulate C table as python list ? In-Reply-To: <1232237191.7347.18.camel@gondor> References: <1232237191.7347.18.camel@gondor> Message-ID: <7B013DE0-748C-4BAF-99B9-907417D9F1D0@cwi.nl> On 18-Jan-2009, at 01:06 , Marc wrote: > I would like to use a C program which manipulates table > as a python module acting on a list. Marc, if you're doing this for speed you may want to look at Numeric Python . They have a set of array-like objects that are (a) pretty standard from a Python point of view and (b) pretty efficient from a C point of view. As soon as you're doing serious number crunching the NumPy arrays will run circles around any code that converts between Python lists and C arrays, because there isn't any conversion done. NumPy arrays are used by all sorts of other libraries that have large numeric datasets (think audio processing, etc). Also, for the algorithms you've sketched in your example you don't even have to write any code in C: it's all there in NumPy already. -- Jack Jansen, , http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From marcglec at free.fr Mon Jan 19 18:52:33 2009 From: marcglec at free.fr (Marc) Date: Mon, 19 Jan 2009 18:52:33 +0100 Subject: [capi-sig] How to manipulate C table as python list ? In-Reply-To: <87eiz1f145.fsf@mulj.homelinux.net> References: <1232237191.7347.18.camel@gondor> <87eiz1f145.fsf@mulj.homelinux.net> Message-ID: <1232387553.6924.1.camel@gondor> Thx to all for your answers, I'm sure I will succeed now :) Marc. Le dimanche 18 janvier 2009 ? 09:51 +0100, Hrvoje Niksic a ?crit : > Marc writes: > > > I would like to use a C program which manipulates table > > as a python module acting on a list. > > My C code is the following: > > int sum(int *tab, int n) > > { > > int i, s = 0; > > > > for (i=0; i > { > > s += tab[i]; > > } > > > > return s; > > } > > Now, I would like to use it as a python module > > where tab would be a python list. > > I read some examples in the documentation but > > the size of the list is always assumed to be known > > such that one can use PyArg_ParseTuple > > with a format description for each argument. > > In this case you only use PyArg_ParseTuple to get to the object that > represents the list. In fact, since you only need one argument, you > don't need PyArg_ParseTuple at all, simply declare your function to > take one argument using the METH_O in the function description, and > code it like this: > > PyObject *sum(PyObject *ignored, PyObject *lst) > { > int i, s = 0; > if (!PyList_Check(lst)) { > PyErr_Format(PyExc_TypeError, "sum: expected list, got %s", > lst->ob_type->tp_name); > return NULL; > } > for (i = 0; i < PyList_GET_SIZE(lst); i++) { > ... sum the list ... > return PyInt_FromLong(s); > } > > > My question is: > > which option should I use with PyArg_ParseTuple? > > If your function is declared to take one argument with METH_O, you > don't need PyArg_ParseTuple at all. If it's declared to take a > variable number of arguments, you'd use it like this: > > PyObject *sum(PyObject *ignored, PyObject *args) > { > int i, s = 0; > PyObject *lst; > if (!PyArg_ParseTuple(args, "O", &lst)) > return NULL; > ... > } > From zouxianjun at huawei.com Thu Jan 22 09:00:06 2009 From: zouxianjun at huawei.com (zouxianjun 45728) Date: Thu, 22 Jan 2009 16:00:06 +0800 Subject: [capi-sig] =?gb2312?b?u9i4tCA6UmU6ICBTb21lIHByb2JsZW0gd2hlbiBp?= =?gb2312?b?IHVzZSBQeXRob24gQy9BUEkgdG8gZW1iZWQgcHl0aG9uIHNjcmlwdCwgbmVl?= =?gb2312?b?ZCBIZWxwLi4uLi4u?= In-Reply-To: <00E98DDD-138F-4AFB-B39A-5AB30D15025E@cwi.nl> References: <00E98DDD-138F-4AFB-B39A-5AB30D15025E@cwi.nl> Message-ID: Thank you very much!!I resolved the problem after i install the new version Python(2.6.1).After i installed the new version, i check the binascii.so again, ldd -r binascii.so, everything goes right.... thank you very much..... ****************************************************************************************** This email and its attachments contain confidential information from HUAWEI, which is intended only for the person or entity whose address is listed above. Any use of the information contained here in any way (including, but not limited to, total or partial disclosure, reproduction, or dissemination) by persons other than the intended recipient(s) is prohibited. If you receive this email in error, please notify the sender by phone or email immediately and delete it! ***************************************************************************************** ----- ??? ----- ???: Jack Jansen ??: ???, ?? 7?, 2009 ??5:07 ??: Re: [capi-sig] Some problem when i use Python C/API to embed python script, need Help...... ???: zouxianjun 45728 ??: capi-sig at python.org > > On 5-Jan-2009, at 08:08 , zouxianjun 45728 wrote: > > > when the program run as exe, everything goes right, but if i > compile > > the program as a .so lib, use other program to load the .so lib > and > > run, it goes wrong,in the lib i also use > PyRun_SimpleString("import > > base64"); it goes wrong.....my python version is 2.3, i want to > know > > what's the problem...... PyErr_Print() print the error info > > below: > > Traceback (most recent call last): > > File "./myModule111.py", line 3, in ? > > import base64 > > File "/usr/lib/python2.3/base64.py", line 7, in ? > > import binascii > > ImportError: /usr/lib/python2.3/lib-dynload/binascii.so: > undefined > > symbol: PyExc_TypeError > > > > i check the binascii.so, ldd -r binascii.so, this lib really has > > > many undefined symbols include PyExc_TypeError, but the problem > is > > when the program is executable, it can goes fine...... > > > > when i compile the program as .so lib, i add -Xlinker -export- > > dynamic, it doesn't solve the problem......... > > Ah, the joys of dynamic linkers... > > You'll need to specify the exact version of your operating system > (probably Linux, but maybe MacOSX or some other unix variant?), > and, > for completeness, your compiler and linker version. > > Sometimes symbols in the base executable are available to all > dynamically loaded modules, but symbols in modules that are > themselves > loaded dynamically not. This seems to be what's biting you. > > Oh yes: can you try a newer version of Python? I fixed a similar > error > for Python on MacOSX at some point in the past, it could be that > you're looking at an error has been fixed in the mean time, 2.3 is > > pretty old by now. > > > -- > Jack Jansen, , http://www.cwi.nl/~jack > If I can't dance I don't want to be part of your revolution -- > Emma > Goldman > > > From philipp at achtziger.de Fri Jan 23 16:49:32 2009 From: philipp at achtziger.de (Philipp Heuser) Date: Fri, 23 Jan 2009 16:49:32 +0100 Subject: [capi-sig] Strange Python behaviour after C-Function Message-ID: <4979E70C.70002@achtziger.de> Hi all, thanks for the numerous replies to my previous questions. Everything in C works fine so far, but there is a very strange behaviour in python after visiting the C-Function. The return value of my C-Function is a list of floats. I can print that list, I can do: a=0 while a References: <4979E70C.70002@achtziger.de> Message-ID: <4979EF10.2080708@achtziger.de> Sorry for bothering you, I just made a stupid error in C, mixing up variable names, so one of the returned lists had the wrong content and wrong length... strange python behaviour anyway... Philipp Philipp Heuser schrieb: > Hi all, > > thanks for the numerous replies to my previous questions. > > Everything in C works fine so far, but there is a very strange > behaviour in python after visiting the C-Function. > > The return value of my C-Function is a list of floats. I can print > that list, I can do: > > a=0 > while a print list[a] > a=a+1 > > works fine, but if try to do > > for element in list: > print element > > It does that as well, but as soon as the end of the list is reached, I > do get an IndexError: list assignment index is out of range. > Surprisingly I do get that as well with any list, where I try to use > the for loop after using the C-function. So if I use an arbitrary list > like > > ll=[1,2,3] > for l in ll: > print l > > I do get the same error, and I don't before calling the C-function... > > Does that sound familiar to anybody? Is that caused by one of the > decref/incref things? > Kind regards > Philipp > _______________________________________________ > capi-sig mailing list > capi-sig at python.org > http://mail.python.org/mailman/listinfo/capi-sig > From ggpolo at gmail.com Fri Jan 23 19:39:10 2009 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 23 Jan 2009 16:39:10 -0200 Subject: [capi-sig] Strange Python behaviour after C-Function In-Reply-To: <4979E70C.70002@achtziger.de> References: <4979E70C.70002@achtziger.de> Message-ID: On Fri, Jan 23, 2009 at 1:49 PM, Philipp Heuser wrote: > Hi all, > > thanks for the numerous replies to my previous questions. > > Everything in C works fine so far, but there is a very strange behaviour in > python after visiting the C-Function. > > The return value of my C-Function is a list of floats. I can print that > list, I can do: > > a=0 > while a print list[a] > a=a+1 > > works fine, but if try to do > > for element in list: > print element > > It does that as well, but as soon as the end of the list is reached, I do > get an IndexError: list assignment index is out of range. > Surprisingly I do get that as well with any list, where I try to use the for > loop after using the C-function. So if I use an arbitrary list like > > ll=[1,2,3] > for l in ll: > print l > > I do get the same error, and I don't before calling the C-function... > > Does that sound familiar to anybody? It sounds like you are not being careful when coding the C function, maybe you forgot to clear some exception or maybe it was supposed to raise an exception but didn't. Can you paste its code ? > Is that caused by one of the > decref/incref things? > Kind regards > Philipp -- -- Guilherme H. Polo Goncalves From gdtunali at yahoo.com Tue Jan 27 03:56:31 2009 From: gdtunali at yahoo.com (Gamze Tunali) Date: Mon, 26 Jan 2009 18:56:31 -0800 (PST) Subject: [capi-sig] Passing an object from script to C code Message-ID: <204458.73727.qm@web32401.mail.mud.yahoo.com> Hi, As a beginner, I have a question about passing a class instance from Python script to my C code. What I am doing is basically creating a class in the script: class dbvalue: def __init__(self, index, type): self.id = index # unsigned integer self.type = type # string last_roi = dbvalue(id, type); bmdl_batch.set_input_from_db(1, last_roi); <-------- I would like to call my C function with last_roi and able to recover id and type in the code. The C part is follows: PyObject *set_input_from_db(PyObject* self, PyObject *args) { unsigned input; PyObject *obj; if (!PyArg_ParseArg(args, "iO:set_input_from_db", &input, &obj)) return NULL; .... } I am not sure if PyArg_ParseArg() is the right method to get the object. I used "O:.." to get it but after that, how do I acces index and type fields of the object. Do I create an equivalent class/struct in C code to? Again, all I want is pass the 2 values together in an object and able to recover then in C code. Thanks, Gamze From theeth at yahoo.com Tue Jan 27 04:45:19 2009 From: theeth at yahoo.com (Martin Poirier) Date: Mon, 26 Jan 2009 19:45:19 -0800 (PST) Subject: [capi-sig] Passing an object from script to C code In-Reply-To: <204458.73727.qm@web32401.mail.mud.yahoo.com> Message-ID: <373060.20049.qm@web51310.mail.re2.yahoo.com> Hi, --- On Mon, 1/26/09, Gamze Tunali wrote: > From: Gamze Tunali > Subject: [capi-sig] Passing an object from script to C code > To: capi-sig at python.org > Date: Monday, January 26, 2009, 9:56 PM > > As a beginner, I have a question about passing a class > instance from Python script to my C code. > What I am doing is basically creating a class in the > script: > > class dbvalue: > def __init__(self, index, type): > self.id = index # unsigned integer > self.type = type # string > > last_roi = dbvalue(id, type); > bmdl_batch.set_input_from_db(1, last_roi); <-------- > > I would like to call my C function with last_roi and able > to recover id and type in the code. The C part is follows: > > > PyObject *set_input_from_db(PyObject* self, PyObject *args) > { > unsigned input; > PyObject *obj; > > if (!PyArg_ParseArg(args, > "iO:set_input_from_db", &input, &obj)) > return NULL; > > .... > } > > I am not sure if PyArg_ParseArg() is the right method to > get the object. It will work, but you should use PyArg_ParseTuple[1] instead, for the reasons explained in the api reference[2]. [1] http://docs.python.org/c-api/arg.html#PyArg_ParseTuple [2] http://docs.python.org/c-api/arg.html#PyArg_Parse > I used "O:.." to get it but after > that, how do I acces index and type fields of the object. Do > I create an equivalent class/struct in C code to? Again, all > I want is pass the 2 values together in an object and able > to recover then in C code. You can use PyObject_GetAttr (or PyObject_GetAttrString) from the Object protocol [3] to access attributes of an object. Once you got your attribute, lets say your id field is a Python Integer which you want to convert to a C int, you can use the Integer object layer for that [4]. [3] http://docs.python.org/c-api/object.html [4] http://docs.python.org/c-api/int.html Hopefully, that pointed you in the right direction. Martin From python_capi at behnel.de Tue Jan 27 09:15:20 2009 From: python_capi at behnel.de (Stefan Behnel) Date: Tue, 27 Jan 2009 09:15:20 +0100 (CET) Subject: [capi-sig] Passing an object from script to C code In-Reply-To: <204458.73727.qm@web32401.mail.mud.yahoo.com> References: <204458.73727.qm@web32401.mail.mud.yahoo.com> Message-ID: <40158.213.61.181.86.1233044120.squirrel@groupware.dvs.informatik.tu-darmstadt.de> Gamze Tunali wrote: > As a beginner, I have a question about passing a class instance from > Python script to my C code. > What I am doing is basically creating a class in the script: > > class dbvalue: > def __init__(self, index, type): > self.id = index # unsigned integer > self.type = type # string > > last_roi = dbvalue(id, type); > bmdl_batch.set_input_from_db(1, last_roi); <-------- > > I would like to call my C function with last_roi and able to recover id > and type in the code. The C part is follows: You might want to leave these things to Cython: cdef class dbvalue: def __init__(self, index, type): > self.id = index # unsigned integer > self.type = type # string > > > PyObject *set_input_from_db(PyObject* self, PyObject *args) > { > unsigned input; > PyObject *obj; > > if (!PyArg_ParseArg(args, "iO:set_input_from_db", &input, &obj)) > return NULL; > > .... > } > > I am not sure if PyArg_ParseArg() is the right method to get the object. I > used "O:.." to get it but after that, how do I acces index and type > fields of the object. Do I create an equivalent class/struct in C code to? > Again, all I want is pass the 2 values together in an object and able to > recover then in C code. > > Thanks, > > Gamze > > > > > _______________________________________________ > capi-sig mailing list > capi-sig at python.org > http://mail.python.org/mailman/listinfo/capi-sig > From python_capi at behnel.de Tue Jan 27 09:20:11 2009 From: python_capi at behnel.de (Stefan Behnel) Date: Tue, 27 Jan 2009 09:20:11 +0100 (CET) Subject: [capi-sig] Passing an object from script to C code In-Reply-To: <204458.73727.qm@web32401.mail.mud.yahoo.com> References: <204458.73727.qm@web32401.mail.mud.yahoo.com> Message-ID: <46217.213.61.181.86.1233044411.squirrel@groupware.dvs.informatik.tu-darmstadt.de> (sorry, accidentally hit 'send') Gamze Tunali wrote: > As a beginner, I have a question about passing a class instance from > Python script to my C code. > What I am doing is basically creating a class in the script: > > class dbvalue: > def __init__(self, index, type): > self.id = index # unsigned integer > self.type = type # string > > last_roi = dbvalue(id, type); > bmdl_batch.set_input_from_db(1, last_roi); <-------- > > I would like to call my C function with last_roi and able to recover id > and type in the code. You may want to leave these things to Cython: cdef class dbvalue: cdef unsigned int id cdef str type def __init__(self, index, type): self.id = index # will raise an exception if not uint self.type = type.encode('ASCII') ... class ...: def set_input_from_db(self, someval, dbvalue value): print someval, value.id, value.type Cython will translate this to efficient C code for you. http://cython.org/ Stefan