我有一个独特的用例,其中我在C ++应用程序中使用CoreBluetooth。关于目标c,有很多关于CoreBluetooth实现的旧教程,我的代码对this来说很熟悉。我的问题是,初始化CBCentralManager后,没有调用centralManagerDidUpdateState
。
c ++的wrapper.h文件
// this file defines c++ functions to be used in the .mm file
void *get_object();
目标c的.h文件
#import "wrapper.h"
@interface MyObject : NSObject <CBCentralManagerDelegate, CBPeripheralDelegate>
@property(strong, nonatomic) CBCentralManager *centralManager;
- (id)init;
- (void)initialize_manager;
@end
。mm文件
// declared in wrapper.h, this is a c++ method to return a void pointer to MyObject
void *get_object() {
void *obj_ptr = [[MyObject alloc] init];
return obj_ptr;
}
// this is the objective c code
@implementation MyObject
- (id)init {
self = [super init];
if (self) {
// this is where the central manager should be created
[self initialize_manager];
}
return self;
}
- (void)initialize_manager {
_centralManager = [[CBCentralManager alloc] initWithDelegate:self
queue:nil
options:nil];
}
// this should get called immediately after initialize_manager
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
std::cout << "this never gets called" << std::endl;
NSLog(@"this never gets called");
。cpp文件进行测试
void *p = get_object();
代码摘要:在我的.cpp文件中,我正在调用get_object(),它会初始化一个新的MyObject并返回指向它的void指针。初始化新的MyObject时,它将调用initialize_manager(),但应该(但当前未调用)调用centralManagerDidUpdate。
Previous issue I found of centralManagerDidUpdateState not being called:他们的问题是他们没有将中央管理器分配给实例变量。但是,我这样做似乎不适用于我。
[不知道这是否是Objective-C ++无法正确处理委托的问题,还是将MyObject作为void *指针存储会引起一些内部魔术。
也可能是因为我的程序退出太早了?我所见过的CoreBluetooth的每种实现都在ViewController中使用,我可以在C ++中复制视图控制器的非终止方面吗?也许与异步问题有关?将不胜感激任何指针!
更新1:我认为CoreBluetooth可能与主c ++应用程序共享同一线程
暂时发布此简短答案,将进行更清晰的迭代编辑。问题是目标c库(CoreBluetooth)需要在与我的主应用程序不同的线程上运行。
敬请期待代码实施