Adding a 'struct' into new python type

Lakshmipathi.G lakshmipathi.g at gmail.com
Sun Mar 8 12:51:27 EDT 2015


Hi Jason,

Thanks for the response. Okay, Will try to convert 'struct test' into
new python object (say 'PyStructTest') and include it inside
CountDictType as pyobject instead of 'struct'.
Will post details here, If i encounter any issues.
----
Cheers,
Lakshmipathi.G
FOSS Programmer.
www.giis.co.in/readme.html


On Sat, Mar 7, 2015 at 9:23 PM, Jason Swails <jason.swails at gmail.com> wrote:
>
>
> 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



More information about the Python-list mailing list