gpt4 book ai didi

multithreading - 在带有 Objective-C++ GUI 的 C++ 应用程序中找不到 Cocoa GUI 线程

转载 作者:行者123 更新时间:2023-12-03 17:26:11 28 4
gpt4 key购买 nike

我有一个没有 GUI 的多 posix 线程 Linux C++ 应用程序,我希望能够在其中偶尔使用 Cocoa 控件,即文件上传/下载对话框和警报。

我远非 Cocoa 专家,但能够构建一些按预期工作的 Objective-C++ 测试/演示应用程序。

现在我已经将 Cocoa 代码集成到我的应用程序中,似乎我在将内容发布到主 GUI 线程时遇到了问题。也许我没有做我需要做的事情来创建一个,我真的不确定。这是我的 .mm 文件中的内容:

#ifdef MACOS
@interface CocoaInterface : NSObject
{
}
- (id) init;
- (void) ShowFileUploadDialog;
- (void) ShowFileDownloadDialog;
@end

@implementation CocoaInterface
- (id) init
{
cout << "Creating NSAutoreleasePool" << endl;
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
cout << "Creating NSApplication" << endl;
NSApplication* app = [[NSApplication alloc] init];
cout << "Calling NSApplication::finishLaunching" << endl;
[app finishLaunching];
[super init];
return self;
}

- (void) ShowFileUploadDialog
{
cout << "Entering ShowFileUploadDialog" << endl;
if ([NSThread isMainThread])
{
// Show file dialog
cout << "Calling NSRunAlertPanel" << endl;
NSRunAlertPanel(@"This is a test", @"Does it work?", @"Yes", @"No", @"");
}
else
{
//NSRunAlertPanel(@"This is a test", @"Does it work?", @"Yes", @"No", @"");
cout << "Redirecting ShowFileUploadDialog call to main thread." << endl;
[self performSelectorOnMainThread:@selector(ShowFileUploadDialog) withObject:nil waitUntilDone:YES];
}
}

- (void) ShowFileDownloadDialog
{
cout << "Entering ShowFileDownloadDialog" << endl;
if ([NSThread isMainThread])
{
// Show file dialog
cout << "Calling NSRunAlertPanel" << endl;
NSRunAlertPanel(@"This is a test", @"Does it work?", @"Yes", @"No", @"");
}
else
{
//NSRunAlertPanel(@"This is a test", @"Does it work?", @"Yes", @"No", @"");
cout << "Redirecting ShowFileDownloadDialog call to main thread." << endl;
[self performSelectorOnMainThread:@selector(ShowFileDownloadDialog) withObject:nil waitUntilDone:YES];
}
}
@end
#endif

我从处理传入网络消息的各个线程中的代码中调用它:

cout << "Creating CocoaInterface." << endl;
CocoaInterface* interface = [[CocoaInterface alloc] init];
cout << "Calling CocoaInterface::ShowFileDownloadDialog." << endl;
[interface ShowFileDownloadDialog];

这会在尝试执行选择器时挂起——就好像它永远无法真正找到主线程一样。 GDB 中的回溯显示我永远等待信号量。

当我在 PerformSelectorOnMainThread 调用之前取消注释 NSRunAlertPanel 调用时,我会在对话框的形状中看到一个白色 block ,但它不会完全绘制或处理任何消息,大概是因为它不在主 GUI 线程上。

我似乎没有合适的 GUI 线程,或者只是无法从我所在的位置访问它。我怀疑我在初始化过程中遗漏了一些东西。有什么建议吗?

最佳答案

您应该调用 NSApplicationLoad() 来处理实例化并为您创建事件循环,而不是显式创建 NSApplication 对象。

如果需要,您还可以使用 NSLog(@"Some string") 函数来代替所有这些 cout

关于multithreading - 在带有 Objective-C++ GUI 的 C++ 应用程序中找不到 Cocoa GUI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4382682/

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