gpt4 book ai didi

c++ - 如何从 Objective C 调用我的 Qt/C++ Dylib?

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:27 24 4
gpt4 key购买 nike

我在 Qt/C++ 中编译了一个 dylib。我创建了一个名为 test() 的简单类方法,它读取字符串输入并返回带有 "-response" 的字符串输出。现在,我如何在 XCode 7(默认的 Cocoa 应用程序)中将其加载到 Objective C 中并使其通过 NSLog() 发出 test()

这是我的构建文件夹在 Qt/C++ 中的样子。

enter image description here

最佳答案

您需要使用 Objective-C++ 类,它是 Objective-C 和 C++ 的混合体。

在主要使用 Objective-C 的项目中使用一个或多个 Objective-C++ 类的最大挑战是避免将 C++ 类暴露给 Objective-C 类。因此,您需要避免在 Objective-C++ 头文件中使用 C++,而只在实现文件中包含 C++。

例如:

CppWrapper.h:

#import <Foundation/Foundation.h>

@interface CppWrapper : NSObject
- (BOOL)callCppMethodA:(int)param;
@end

CppWrapper.mm:

#import "CppWrapper.h"
#import "cppclass.h" // C++

@interface CppWrapper()
{
cppclass *_cppclass; // C++
}
@end

@implementation CppWrapper

- (id)init
{
self = [super init];
if (self) {
_cppclass = new cppclass(); // C++
}
return self;
}

- (void)dealloc
{
delete _cppclass; // C++
}

- (BOOL)callCppMethodA:(int)param
{
return _cppclass->methodA(param); // C++
}

@end

像这样使用它:

CppWrapper *cppWrapper = [CppWrapper new];
[cppWrapper callCppMethodA:123];

关于c++ - 如何从 Objective C 调用我的 Qt/C++ Dylib?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34121291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com