目标C对象作为C ++类中的实例变量

咸坚果

我试图以一种方式来修改C ++类,以使Objective C对象是其实例变量之一。

从本质上讲,这个问题与这相反:C ++类作为Objective-C类的实例变量

头文件MyCPPClass.h如下所示:

namespace my_namespace{

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

     private:
         void otherFunc();
    };
}

MyCPPClass.mm文件看起来像这样:

#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!");
}

这里的问题是,我需要存储对在中创建的对象的引用someFunc(),然后在中使用它otherFunc()该对象是的实例NSURLSessionTask我在C ++中的背景非常有限:(。这样做的最少干扰方式是什么?

盖瑟曼

我相信您可以将其存储为void *,根据此方法,可以将Objective-C对象作为void *指针传递给函数

因此,您的标头将变为:

namespace my_namespace{

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

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

如果要向其发送消息,则首先将其投射回原本应为的状态:

[(NSURLSessionTask*)mySessionTask someMessageWithArg: foo]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章