【问题标题】:calling objective C method in callback function [duplicate]在回调函数中调用目标C方法[重复]
【发布时间】:2014-03-23 02:51:26
【问题描述】:

我一直在使用 Dragonmobile sdk 和 Audio Sound System,试图做语音识别 -> 文本到语音链。

这是我的代码:

(这里有语音识别部分)

- (void)recognizer:(SKRecognizer *)recognizer didFinishWithResults:{ 
...
SystemSoundID id = [self playSound:url2]; //playSound
    AudioServicesAddSystemSoundCompletion (
                                           id,
                                           NULL,
                                           NULL,
                                           detectSoundFinish,
                                           NULL
                                           );
...
}

- (void)performRecognition:(id)sender
{
    if (!recognizer){
        self.recognizer = [[SKRecognizer alloc] initWithType:SKDictationRecognizerType detection:SKLongEndOfSpeechDetection language:@"en_US" delegate:self];
    }
}

void detectSoundFinish ( SystemSoundID  ssID, void *clientData )
{
    printf("end\n");
    //I want to call performRecognition here, or an equivalent thing.
}

我是 Objective C 的新手(甚至是 C。我主要用 Python 编写代码),我知道回调函数不属于我的班级。所以,我的问题是 1.有没有办法在回调函数中调用objc方法? 2.或者,一种从回调中访问主类属性的方法? 我一直在搜索和尝试一整天,但还没有弄清楚如何做到这一点。 谢谢!

【问题讨论】:

  • Objective-C 中的正常做法是使用“委托”类而不是函数指针进行回调。如果需要函数指针以与某些非 Objective-C 工具集兼容,则要做的事情是使用常规 C 或 C++ 工具,然后链接到 Objective-C,类似于 Merlevede 所描述的。

标签: ios objective-c c


【解决方案1】:

您不能将 Objective-C 函数用作 C 函数的回调。

您可以做的是使用最后一个参数,旨在传递您想要的任何数据,将指针传递给您的类实例。

AudioServicesAddSystemSoundCompletion (id,
                                       NULL,
                                       NULL,
                                       MyAudioServicesSystemSoundCompletionProc,
                                       self);

在 C 回调函数体内,将指针转换为您的类,然后使用它!

void MyAudioServicesSystemSoundCompletionProc (SystemSoundID ssID, void *clientData);
{
    MyClass *obj = (MyClass*)clientData;
    // use obj in the normal Objective-C way!!!
}

【讨论】:

  • You cannot use an Objective-C function as a callback to a C function. 不正确!获取事物的 IMP 函数指针,您可以将其传递给任何接受适当签名的 C 函数。
猜你喜欢
  • 1970-01-01
  • 2011-09-27
  • 2013-06-24
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 2021-08-29
  • 2018-07-14
  • 1970-01-01
相关资源
最近更新 更多