繁体   English   中英

在C ++ CLI中创建公共字符串

[英]Create a public string in C++ CLI

我有2节课。 我在C ++ / CLI中使用System::Speech::recognition 现在,我在事件处理程序的末尾:

recognizer->SpeechRecognized += gcnew EventHandler<SpeechRecognizedEventArgs^>(sre_SpeechRecognized);

我也有回调函数:

void sre_SpeechRecognized(Object^ sender, SpeechRecognizedEventArgs^ e)
{
    // Do something
}

这引发了一个错误:

Invalid Delegate initializer -- Function is no Member of a managed-class

知道为什么,以及如何解决它?

另一个(相关)问题:

sre_SpeechRecognized()应该将结果值分配给String变量。

现在:该字符串变量在同一类中声明: public: String^ res_SR = "" ,C ++ CLI也为此感到讨厌。 (以某种方式我没有std::string ,只有System::String ...)

关于如何解决这两个问题的任何想法吗?

编辑(以防我的代码片段有帮助):

ref class tsapi
{
    void recogn_speech() {
        SpeechRecognizer^ recognizer = gcnew SpeechRecognizer();

        Choices^ commands_vc = gcnew Choices();
        commands_vc->Add(gcnew array<String^> { "Move", "To" });

        GrammarBuilder^gb = gcnew GrammarBuilder();
        gb->Append(commands_vc);

        Grammar^ g = gcnew Grammar(gb);
        recognizer->LoadGrammar(g);

        // Register Event
        recognizer->SpeechRecognized += gcnew EventHandler<SpeechRecognizedEventArgs^>(sre_SpeechRecognized);
    }

    void sre_SpeechRecognized(Object^ sender, SpeechRecognizedEventArgs^ e)
    {
        String^ res = e->Result->Text->ToString();
    }
};

.Net没有“全局功能”的概念。 一切都必须包含在一个类中。 C ++ / CLI编译器将采用一些看起来像全局变量的方法和变量,并将它们作为静态成员保留在特殊类中,但显然不是全部。 将您正在执行recognizer->SpeechRecognized += ...的代码放入一个类( ref class ,所以它是一个托管类),并将sre_SpeechRecognized也放入sre_SpeechRecognized中。

对于字符串分配错误,您需要将分配从类定义移至构造函数中。 与C ++一样,C ++ / CLI不允许在类定义中分配实例变量。 但是,我将考虑取消显式分配:由于要分配空字符串,因此请考虑将字段保留为nullptr ,这是.Net默认情况下要确保的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM