문제

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?

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top