加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

对类型的非const左值引用 – 使用Class类型的参数时,Objective-C

发布时间:2020-12-16 07:23:23 所属栏目:百科 来源:网络整理
导读:我有两个用Objective-C编写的包装类,用于它们的等效C类.我们称它们为OABCClass和OXYZCallbackInterface.现在我在C(ABCClass)中有一个方法,其中一个参数是一个接口-XYZCallbackInterface. 例如 : std::string methodWithArguments(std::string req,CommonNam
我有两个用Objective-C编写的包装类,用于它们的等效C类.我们称它们为OABCClass和OXYZCallbackInterface.现在我在C(ABCClass)中有一个方法,其中一个参数是一个接口-XYZCallbackInterface.

例如 :

std::string methodWithArguments(std::string req,CommonNamespace::XYZCallbackInterface &callback);

在我的Objective-C包装类中,即OABCClass,我上面提到的C方法的方法实现如下:

-(NSString *)methodWithArguments(NSString*)req  callback(OXYZCallbackInterface*)callback {
    std::string res = cppClassVariable->methodWithArguments(req.UTF8String,callback);
}

我在这里得到错误:

Non-const lvalue reference to type ‘Common::XYZCallbackInterface’ cannot bind to a temporary of type ‘Common::XYZCallbackInterface *’

使用它的正确方法是什么?任何帮助表示赞赏.

//Objective-C++ side
  #ifndef OXYZCallbackInterface_h
  #define OXYZCallbackInterface_h
  #import <Foundation/Foundation.h>

  //.h
  @interface OXYZCallbackInterface : NSObject

  -(bool)onResponseAvailable:(NSString* )response;

  @end
  #endif /* OXYZCallbackInterface_h */

  //.mm
  #import "OXYZCallbackInterface.h"
  #include "Common/Common.Shared/OXYZCallbackInterface.h"

  using namespace CommonNamespace;

  @implementation OXYZCallbackInterface

  - (instancetype)init
  {
   self = [super init];
     return self;
  }

  -(bool)onResponseAvailable:(NSString* )response{
     bool isResp = _objIPICCallback->onResponseAvailable(response.UTF8String);
    return isResp;
 }

  @end

  //C++ side
  #pragma once

  #include "DataTypes.h"

 namespace CommonNamespace
 {
 class XYZCallbackInterface
 {
 public:
    virtual ~ XYZCallbackInterface() {}
    virtual bool onResponseAvailable(std::string response) = 0;
 };
}

OABCClass.mm实现如下:

-(NSString*) methodWithArguments(NSString*)req  callback(OXYZCallbackInterface*)callback{
   NSString* result = @"";

   _pOABC -> methodWithArguments("",(__bridge XYZCallbackInterface*)callback);

   //  Error : Non-const lvalue reference to type CommonNamespace::XYZCallbackInterface cannot bind to a temporary of type CommonNamespace::XYZCallbackInterface *

   return result;
}

解决方法

您没有显示您的OXYZCallbackInterface Objective-C类,因此很难确定它是如何“包装”XYZCallbackInterface C接口的.但是,OXYZCallbackInterface不是XYZCallbackInterface(在面向对象的“is-a”意义上)是肯定的. OXYZCallbackInterface的实例不是XYZCallbackInterface(或任何子类)的实例.因此,您不能将指向OXYZCallbackInterface实例的指针传递给期望引用XYZCallbackInterface实例的函数.

你的包装器必须提供一种解包方法,并返回指向它包装的原始XYZCallbackInterface对象的指针或引用.让我们说它有这个签名:

- (XYZCallbackInterface*) original;

然后,您可以这样调用C方法:

std::string res = cppClassVariable->methodWithArguments(req.UTF8String,*[callback original]);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读