Adding a 'struct' into new python type

Jason Swails jason.swails at gmail.com
Sat Mar 7 10:53:05 EST 2015


On Sat, Mar 7, 2015 at 4:15 AM, Lakshmipathi.G <lakshmipathi.g at gmail.com>
wrote:

> Hi,
>
> I'm following this example :
> http://nedbatchelder.com/text/whirlext.html#h_making_a_type and trying
> to add
> new data into 'CountDict' type
>
> Adding a simple 'char' works well.
>
> typedef struct {
>    PyObject_HEAD
>    PyObject * dict;
>    int count;
>    char c;  //add this and placed an entry into PyMemberDef as T_CHAR.
> } CountDict;
>
> I can access  'c' from python code,no issues so far.
>
> Now I want to added 'struct type' into this 'CountDict' type.
> struct test {
> int x;
> };
>
> typedef struct {
>    PyObject_HEAD
>    PyObject * dict;
>    int count;
>    char c;
>    struct test t1; //?? how to add this
> } CountDict;
> ​​
>>

​​
>
> ​​
> How to do achieve this? (Due to legacy code dependency, I can't use
> ​​
> ctype/cpython etc).
> ​​
> thanks for any help/pointers.
>

​The way *I* would do this is turn struct test into another Python object.
Then instead of defining it in CountDict as type "struct test", define it
as the PyStructTest that you assigned it to when you turned it into a
Python class.

For example, in that website you linked to, CountDict was turned into a
CountDictType Python type.  So do something similar to "test" in which you
turn it into a PyStructTest type in the same way.  Then declare it as a
PyStructTest pointer instead of a struct test.

I'm not sure you can get around an approach like this.  I believe that in
order to access data from Python, it needs to be a Python type.  The
struct-to-Python-type conversion *knows* how to translate basic types, like
char, double, float, int, and long into their Python equivalents; but it
can't handle something as potentially complicated as an arbitrary struct.
Of course, if all you want to do is access t1 from C, then I think what you
have is fine.

​Good luck,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150307/6a7319e9/attachment.html>


More information about the Python-list mailing list