Cpp-Swift Interop 因与 NSObject 的一致性而失败

问题描述 投票:0回答:1

我有一个项目,我正在从 swift5.9 中引入的 cpp 直接进行 swift 调用。下面是我的 swift 类,其方法在 cpp 上被调用。

import Foundation

public class MySwiftClass
{
   public static func testInterop () -> Void
   {
     NSLog("----------- hey --------")
   }
}

我能够使用上述类在 cpp 中成功调用“testInterop()”,但是如果我在“MySwiftClass”类中添加与 NSObject 的一致性,则下面的 cpp 代码中的 swift 调用将失败并出现错误

命名空间“CoreModule”中没有名为“MySwiftClass”的成员

其中 CoreModule 是我的快速目标。下面是我调用 swift 方法的 Cpp 代码:

#include "temp.hpp"
#include "CoreModule-Swift.h"

void
TempLogger::DisplayTempError ()
{
printf("\nthis is a temporary logger\n");

    CoreModule::MySwiftClass::testInterop ();
}

我无法确定为什么添加 NSObject 一致性会生成此错误。有什么帮助吗?

c++ swift interop
1个回答
0
投票

这里有一些想法:

  1. 如果您想在 C++ 代码中使用 Objective-C(子)类,则需要使用 Objective-C++ 文件,因此您需要将文件扩展名更改为
    .mm
  2. 一旦进入 Objective-C 领域,就不再有命名空间了,因为 Objective-C 不支持它们,所以它只是
    MySwiftClass
    而不是
    CoreModule::MySwiftClass
  3. Objective-C 类使用不同的方法调度机制,称为 消息发送,并且具有不同的语法:
    [MySwiftClass testInterop]

组装以上所有内容,这就是您的

.mm
文件的外观:

#include "temp.hpp"
#include "CoreModule-Swift.h"

void
TempLogger::DisplayTempError ()
{
printf("\nthis is a temporary logger\n");

    [MySwiftClass testInterop];
}
© www.soinside.com 2019 - 2024. All rights reserved.