Domanda

I am trying to write a code of union using ctypes, but it is not giving desired output...

Code given:

#include<stdio.h>
int main()
{
  union a
  { 
    int i;
    char ch[2];
  };
  union a key;
  key.i=512;
  printf("%d\n",key.i);
  printf("%d\n",key.ch[0]);
  printf("%d\n",key.ch[1]);
  return 0;
}

Expected output:

512
0
2

I tried it as:

#Demo of union at work
from ctypes import *
class a(Union):
    _fields_= [("i", c_int, 16),
               ("ch[2]",c_char)]
key=a()
key.i=512
print key.i
print key.ch[0]
print key.ch[1]

AttributeError: 'a' object has no attribute 'ch'

Didn't know why it is giving that error?

Any way to implement it?

È stato utile?

Soluzione

The fields of your union are declared incorrectly. You've declared an attribute named "ch[2]".

To demonstrate this, have a look at this variant of your program:

#Demo of union at work
from ctypes import *
class a(Union):
    _fields_= [("i", c_int, 16),
               ("ch[2]",c_char)]
key=a()
key.i = 65
print getattr(key, "ch[2]")

Output

A

You probably meant to write code like this:

_fields_= [("i", c_int, 16),
           ("ch", c_byte*2)]

This declares ch to be an array of c_byte, with length 2.

Note that I use c_byte in place of c_char because you expect an integral type rather than a character.

So, here's the corrected program:

#Demo of union at work
from ctypes import *
class a(Union):
    _fields_= [("i", c_int, 16),
               ("ch",c_byte*2)]
key=a()
key.i=512
print key.i
print key.ch[0]
print key.ch[1]

Output

512
0
2
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top