Share via


Accessing C or C++ Data in __asm Blocks

OverviewHow Do I

A great convenience of inline assembly is the ability to refer to C or C++ variables by name. An __asm block can refer to any symbols, including variable names, that are in scope where the block appears. For instance, if the C variable var is in scope, the instruction

__asm mov eax, var

stores the value of var in EAX.

If a class, structure, or union member has a unique name, an __asm block can refer to it using only the member name, without specifying the variable or typedef name before the period (.) operator. If the member name is not unique, however, you must place a variable or typedef name immediately before the period operator. For example, the following structure types share same_name as their member name:

struct first_type
{
   char *weasel;
   int same_name;
};

struct second_type
{
   int wonton;
   long same_name;
};

If you declare variables with the types

struct first_type hal;
struct second_type oat;

all references to the member same_name must use the variable name because same_name is not unique. But the member weasel has a unique name, so you can refer to it using only its member name:

__asm
{
   mov ebx, OFFSET hal
   mov ecx, [ebx]hal.same_name ; Must use 'hal'
   mov esi, [ebx].weasel       ; Can omit 'hal'
}

Note that omitting the variable name is merely a coding convenience. The same assembly instructions are generated whether or not the variable name is present.

You can access data members in C++ without regard to access restrictions. However, you cannot call member functions.