Cast from void * to Objective-C object - EXC_BAD_ACCESS code = 2

Discussion in 'Mac Programming' started by moonman239, Mar 29, 2016.

  1. moonman239 macrumors 68000

    Joined:
    Mar 27, 2009
    #1
    I have an Objective-C object named "LocationGetter", and a companion C++ object named "CppLocationGetter". The two objects are properties of each other, and they are supposed to communicate with each other. Unfortunately, when the C++ object sends "startLocationUpdates" to the Objective-C object, an EXC_BAD_ACCESS code 2 error results. Edited to add: The debugger says "CppLocationGetter"'s getter property is of type "observer *", although I did not define that type. Also, the memory address appears to be identical to that of my C++ object's "observer" property.

    LocationGetter.m:
    Code:
    #import "LocationGetter.h"
    
    #ifdef __cplusplus
    
    usingnamespaceCppLocation;
    
    CppLocationGetter::CppLocationGetter()
    
    {
    
        LocationGetter *getter = [[LocationGetter alloc] initWithCppObject:this];
    
        this->getter = (__bridge void *)getter;
    
     
    
    }
    
    void CppLocationGetter::startLocationUpdates()
    
    {
    
        [(__bridgeLocationGetter *)getter startLocationUpdates]; // EXC_BAD_ACCESS
    
    }
    
    #endif
    
    #ifdef __OBJC__
    
    @implementation LocationGetter
    
    {
    
        CppLocation::CppLocationGetter *CppObj;
    
    }
    
    -(instancetype)initWithCppObject:(CppLocationGetter *)getter
    
    {
    
        self = [self init];
    
        if (self) {
    
            CppObj = getter;
    
        }
    
        returnself;
    
    }
    
    -(void)startLocationUpdates
    
    {
    
        CppObj->CppLocationGetter::observer->locationUpdated(10, 01, 10);
    
    }
    
    @end
    
    #endif
    
    LocationGetter.h:
    Code:
    
    
    #ifdef __cplusplus
    
    namespace CppLocation
    
    {
    
    struct CppLocationObserver
    
    {
    
        virtual void locationUpdated(float latitude, float longitude, float accuracy) = 0;
    
    };
    
    class CppLocationGetter {
    
        void *getter;
    
    public:
    
        CppLocationGetter();
    
        CppLocationObserver *observer;
    
        void startLocationUpdates();
    
    };
    
    }
    
    #endif
    
    
    
    #ifdef __OBJC__
    
    #include <Foundation/Foundation.h>
    
    @interface LocationGetter : NSObject
    
    -(instancetype)initWithCppObject:(CppLocation::CppLocationGetter *)getter;
    
    -(void)startLocationUpdates;
    
    @end
    
    #endif
    
     
  2. moonman239 thread starter macrumors 68000

    Joined:
    Mar 27, 2009
    #2
    I fixed it by adding
    Code:
    CFBridgingRetain(getter)
    to my CppLocationGetter constructor. I don't have a CFBridgingRelease call yet, but that might be a good idea.
     

Share This Page