Re: How are C++ objects laid out in memory ?
- From: Tim Roberts <spamtrap@xxxxxxxxxx>
- Date: Fri, 27 May 2005 04:15:43 +0000 (UTC)
"WahJava" <spamtrap@xxxxxxxxxx> wrote:
>
>I'm investigating on how C++ objects can be accessed and invoked by
>the external code (e.g. a C code, or a assembly language routine, or
>some other language routines). I'm using "Microsoft 32-bit C/C++
>Optimizing Compiler v. 13.10.3052". How C++ class is actually
>laid out in memory ?
Matt already gave you very good answers to most of these. I'm only going
to add a few additional comments.
If a C++ class or struct contains no virtual methods, its layout is exactly
identical to the same struct written in C.
>My half correct guess is representation as a structure is
>represented. e.g.
>
>class Msg
>{
> char* msg;
>public:
> Msg(const char*);
> void print();
> ~Msg();
>};
>
>might be represented in C as:
>
>struct MsgStruct
>{
> char* msg;
>
> void (*construct)(struct MsgStruct*, const char*);
> void (*print)(struct MsgStruct*);
> void (*destruct)(struct MsgStruct*);
>};
Nope. The data structure will be:
struct MsgStruct
{
char msg;
}
And there will be public functions created called:
void Msg::Msg( const char * );
void Msg::print( );
void Msg::~Msg( );
There are no function pointers. Calls to xxx->print() can all be linked
statically.
>Suppose I want to expose a C++ object to some C code, although that C
>code can cast my C++ object to a pointer and can change its data, but
>what about member methods. And is there any standard that controls
>this behavior ?
Yes and no. The ISO C++ Standard requires certain behavior that make a
particular layout most natural, and most compilers do it the same way, but
a compiler can do it whatever way it wants, as long as it works the same.
>Is there any table of function
>pointers which I can locate and then invoke the function pointers ?
If the class has virtual methods, then the first dword of the struct is a
pointer to a table of function pointers. For non-virtual methods, the C
code can just use the (decorated) name.
>And by the way, how COM does it ?
Remember that a COM interface has no members, and all of its methods are
virtual. That means a COM interface object consists of exactly 4 bytes,
which contains a pointer to a function table.
Do you have access to Visual C++? Go look at any include file generated by
the IDL compiler. OBJIDL.H is one example. It contains both C++ and C
code to access the methods of its COM objects. That will show you how it
is done.
--
- Tim Roberts, timr@xxxxxxxxx
Providenza & Boekelheide, Inc.
.
- References:
- How are C++ objects laid out in memory ?
- From: WahJava
- How are C++ objects laid out in memory ?
- Prev by Date: Re: Why do we need FlushInstructionCache() ?
- Next by Date: Re: Windows Syscalls !!
- Previous by thread: Re: How are C++ objects laid out in memory ?
- Next by thread: Re: How are C++ objects laid out in memory ?
- Index(es):
Relevant Pages
|