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?

Community
  • 1
  • 1
SaltyNuts
  • 5,068
  • 8
  • 48
  • 80

1 Answers1

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]
Community
  • 1
  • 1
guysherman
  • 581
  • 1
  • 8
  • 20