[Effective-cpp] Item 34: Understand How to Combine C++ and C in the Same Program.

David Sykes davids at revolution.co.uk
Fri Jun 6 06:17:02 EDT 2003


I have done the same, passing c++objects as structs, and it worked a treat. 
I don't know if there is a rule that objects should be represented in the 
same way as structs, though, and if there is not then presumably there is 
the potential for a mismatch.

In both those points I should have used the phrase "directly transfer" for 
objects definitions and objects with virtual functions. In both cases there 
is going to be a struct somewhere, and it is probably structured in the 
same way as C would, so it is going to be possible to transfer, but it may 
be specific to the development system

-----Original Message-----
From:	Klitos Kyriacou [SMTP:Klitos.Kyriacou at reuters.com]
Sent:	06 June 2003 10:45
To:	effective-cpp at accu.org
Subject:	RE: [Effective-cpp] Item 34:  Understand How to Combine C++ and C 
in the Same Program.

Hi.

> Data Structure Compatibility
> ====================
> Object definitions will not compile in C so it is not
> possible to directly
> pass pointers to objects between C and C++. The rules
> governing the layout
> of a struct in C++ are consistent with those of C, however, so it is
> therefore safe to pass pointers to structures back and forth
> between C and
> C++. Adding non virtual functions to the C++ version of the
> struct does not
> change the structure layout, so pointers to structs with non virtual
> functions will transfer between C and C++.

About 7 years ago, in my previous job, we started adding C++ code to an
existing, large application written entirely in C up till then. We had
success deriving our C++ classes from the C structs. We could even pass
C++ objects to existing C functions that expected C structs. Any
disadvantages doing it that way?

> Adding virtual functions,
> however, causes structs to use a different memory layout, and
> transfer is
> no longer possible.

Is this necessarily true? If you slice a derived class that has virtual
functions into a POD, C struct (and pass it to a C function) won't the
resulting struct have the same memory layout as the original?

Regards,
Klitos
[ *** LongSig auto truncated *** ]
_______________________________________________
Effective-cpp mailing list
Effective-cpp at accu.org
http://www.accu.org/mailman/listinfo/effective-cpp

---------------------------------------------------------------------------
Any views or opinions are solely those of the author and do not necessarily represent those of Revolution Software Ltd unless specifically stated.
This email and any files transmitted are confidential and intended solely for the use of the individual or entity to which they are addressed.
If you have received this email in error, please notify postmaster at revolution.co.uk
---------------------------------------------------------------------------



More information about the Effective-cpp mailing list