Unity 使用Win32.RegistryKey的问题
在研究使用Microsoft.Speech.dll做语音命令词识别时,发现将该dll放到Unity工程中使用时会报如下错误:
NullReferenceException: Object reference not set to an instance of an object Microsoft.Speech.Internal.ObjectTokens.RegistryDataKey.HKEYfromRegKey (Microsoft.Win32.RegistryKey regKey) (at <7c2225eddeb441b59b44afbea5394aaf>:0) Microsoft.Speech.Internal.ObjectTokens.RegistryDataKey.RootHKEYFromRegPath (System.String rootPath) (at <7c2225eddeb441b59b44afbea5394aaf>:0) Microsoft.Speech.Internal.ObjectTokens.RegistryDataKey.Open (System.String registryPath, System.Boolean fCreateIfNotExist) (at <7c2225eddeb441b59b44afbea5394aaf>:0) Microsoft.Speech.Internal.ObjectTokens.ObjectTokenCategory.Create (System.String sCategoryId) (at <7c2225eddeb441b59b44afbea5394aaf>:0) Microsoft.Speech.Recognition.SpeechRecognitionEngine.InstalledRecognizers () (at <7c2225eddeb441b59b44afbea5394aaf>:0) Microsoft.Speech.Recognition.SpeechRecognitionEngine..ctor (System.Globalization.CultureInfo culture) (at <7c2225eddeb441b59b44afbea5394aaf>:0)
通过使用ILSpy查看过Microsoft.Speech.dll后发现,有这样的调用顺序:
1. Microsoft.Speech.Recognition.SpeechRecogintionEngine 2. foreach (RecognizerInfo item in InstalledRecognizers()) 3. ObjectTokenCategory.Create("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech Server\\v11.0\\Recognizers")) 4. RegistryDataKey.Open(sCategoryId, fCreateIfNotExist: true); 5. RootHKEYFromRegPath(firstKeyAndParseRemainder); 6. HKEYfromRegKey(registryKey); 7. private static IntPtr HKEYfromRegKey(RegistryKey regKey) { Type typeFromHandle = typeof(RegistryKey); BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic; FieldInfo field = typeFromHandle.GetField("hkey", bindingAttr); SafeHandle safeHandle = (SafeHandle)field.GetValue(regKey); return safeHandle.DangerousGetHandle(); } 8. 到这一步时,需要去查找RegistryKey类中通过反射找的私有变量hkey。 这个在.NET版本的mscorlib中,RegistryKey有如下变量: private SafeRegistryHandle hkey; 而在Unity Editor的安装目录下mscorlib.dll中,是没有这个变量的。这样导致会抛异常。