C++ classes as instance variables of an Objective-C class

后端 未结 5 1160
轻奢々
轻奢々 2021-02-10 06:29

I need to mix Objective-C and C++. I would like to hide all the C++ stuff inside one class and keep all the others plain Objective-C. The problem is that I want to have some C++

5条回答
  •  花落未央
    2021-02-10 07:02

    DO NOT DO THIS

    If you ifdef out an instance variable, that will give two separate instance variable layouts for this class. You will get random memory smashers all over the place because memory allocated for the object in half the cases will be too short. Instead of ifdefing out the instance variable, forward-declare its type like

    struct CPPClass;
    

    and have a pointer to it in the ivar, then in your init/dealloc methods call new/delete to create the object. If you have several objects, you can create a struct to hold all C++ ivars directly and then just new/delete that struct.

    See this thread for more detail and further links to information, including a podcast that talks at length about ObjC++: Can I separate C++ main function and classes from Objective-C and/or C routines at compile and link?

提交回复
热议问题