GNU Info

Info Node: (nasm.info)Section 7.4.4

(nasm.info)Section 7.4.4


Next: Section 7.4.5 Prev: Section 7.4.3 Up: Section 7.4
Enter node , (file) or (file)node

7.4.4. Accessing Data Items
---------------------------

   To get at the contents of C variables, or to declare variables which
C can access, you need only declare the names as `GLOBAL' or `EXTERN'.
(Again, the names require leading underscores, as stated in *Note
Section 7.4.1::.) Thus, a C variable declared as `int i' can be
accessed from assembler as

     extern _i
     
             mov ax,[_i]

   And to declare your own integer variable which C programs can access
as `extern int j', you do this (making sure you are assembling in the
`_DATA' segment, if necessary):

     global  _j
     
     _j      dw      0

   To access a C array, you need to know the size of the components of
the array. For example, `int' variables are two bytes long, so if a C
program declares an array as `int a[10]', you can access `a[3]' by
coding `mov ax,[_a+6]'. (The byte offset 6 is obtained by multiplying
the desired array index, 3, by the size of the array element, 2.) The
sizes of the C base types in 16-bit compilers are: 1 for `char', 2 for
`short' and `int', 4 for `long' and `float', and 8 for `double'.

   To access a C data structure, you need to know the offset from the
base of the structure to the field you are interested in. You can
either do this by converting the C structure definition into a NASM
structure definition (using `STRUC'), or by calculating the one offset
and using just that.

   To do either of these, you should read your C compiler's manual to
find out how it organises data structures. NASM gives no special
alignment to structure members in its own `STRUC' macro, so you have to
specify alignment yourself if the C compiler generates it. Typically,
you might find that a structure like

     struct {
         char c;
         int i;
     } foo;

   might be four bytes long rather than three, since the `int' field
would be aligned to a two-byte boundary. However, this sort of feature
tends to be a configurable option in the C compiler, either using
command- line options or `#pragma' lines, so you have to find out how
your own compiler does it.


automatically generated by info2www version 1.2.2.9