FAQ 36.06 Can a C function directly access data in an object of a C class?

FAQ 36.06 Can a C function directly access data in an object of a C++ class?

Sometimes.

First read the previous FAQ on passing C++ objects to and from C functions. A C++ object's data can be safely accessed from a C function if all of the following are true.

  • The C++ class has no virtual base classes anywhere in the inheritance graph.

  • The C++ class has no virtual functions (including inherited virtual functions).

  • The C++ class has all its data in the same access level section (private:, protected:, or public:).

  • The C++ class has no fully contained member objects that have either virtual functions or virtual base classes.

If the C++ class or its member object have any base classes, accessing the data will be technically nonportable, because the language does not mandate a specific class layout in the presence of inheritance. However, at least with nonvirtual inheritance, all C++ compilers do it the same way the base class subobject appears first (in left-to-right order in the event of multiple inheritance), and member objects follow.

If the class has any virtual base classes, it is more complicated and even less portable.

By far the safer and easier way is to use an access function from C. This costs a function call to access the datum (that is, these calls from C cannot be inlined), but unless the application is CPU bound (see FAQ 33.02), it is probably best to make the application code safe and portable.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net