2

I'm attempting to modify a C++ class in such a way that an Objective C object is one of its instance variables.

In essence, this question is like the reverse of this: C++ classes as instance variables of an Objective-C class

The header file MyCPPClass.h looks like this:

namespace my_namespace{

    class MyCPPClass: public my_namespace::OperationHandler {
     public:
         void someFunc();

     private:
         void otherFunc();
    };
}

And the MyCPPClass.mm file looks like this:

#include "MyCPPClass.h"
#import <Foundation/Foundation.h>

void my_namespace:: MyCPPClass:: someFunc() {
    NSLog(@"I can run ObjC here! Yahoo!");

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"download_url_goes_here"]];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
   // handle the data
   }];

}

void my_namespace:: MyCPPClass:: otherFunc() {
    NSLog(@"I can run ObjC here! Yahoo!");
}

The issue here is that I need to store a reference to an object created in someFunc() and then use it in otherFunc(). This object is an instance of NSURLSessionTask. My background in C++ is very limited :(. What is the least intrusive way to do this?

1 Answer 1

1

I believe you can store it as a void*, according to this Pass an Objective-C object to a function as a void * pointer

So your header would become:

namespace my_namespace{

    class MyCPPClass: public my_namespace::OperationHandler {
        public:
            void someFunc();

        private:
            void otherFunc();
            void *mySessionTask;
    };
}

If you want to send a message to it you first cast it back to what it is supposed to be:

[(NSURLSessionTask*)mySessionTask someMessageWithArg: foo]
Sign up to request clarification or add additional context in comments.

1 Comment

But then you lose the memory management of the variable which is based on the type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.