首页 > 解决方案 > 是什么导致 Unity 3D 中的“WrongThreadException”?

问题描述

我想在 Unity 中集成一个 C++ 项目。Unity 提供了一种称为I2CPP(C++ 中间语言)的机制,允许将 C++ 代码添加到您的统一项目中。我在 Visual Studio 的“空白应用程序(通用 Windows C++/CX)”项目中创建了一个简单的 C++ 类和标头。

// header
namespace SomeNamespace {
    public ref class MyRuntimeClass sealed
    {
        public:
            // Constructor
            MyRuntimeClass();

            // Method to check if initialized
            bool IsClassInitialized();

        private:
            bool _isRuntimeInitialized = false;
    };
} 

// implementation
using SomeNamespace;
MyRuntimeClass::MyRuntimeClass()
{
    _isRuntimeInitialized = true;
}

bool MyRuntimeClass::IsClassInitialized()
{
    return _isRuntimeInitialized;
};

我在 Unity 中制作了一个简单的项目,并对文档中概述的 Player 设置进行了必要的更改。我还添加了一个立方体作为游戏对象,并将一个使用我的 C++ 代码的脚本附加到立方体上,即

#if ENABLE_WINMD_SUPPORT
using SomeNamespace;
#endif

public class RuntimeSampleUnity : MonoBehaviour
{
#if ENABLE_WINMD_SUPPORT
    private MyRuntimeClass _myRuntimeClass;
#endif

    // Default MonoBehaviour method
    void Start()
    {
#if ENABLE_WINMD_SUPPORT
        // New instance of runtime class
        _myRuntimeClass = new MyRuntimeClass();

        // Check to see if we initialized C++ runtime component
        var isInit = _myRuntimeClass.IsClassInitialized();
        Debug.LogFormat("MyRuntimeClass: {0}", isInit);
#endif
    }
}

在最后一步中,我已将 C++ 项目中的 winmd 文件添加到我在 Unity 中的资产中。该项目构建良好,但是当我运行该项目时,我得到一个Platform.WrongThreadException: The application called an interface that was marshalled for a different thread. 是什么导致了这个异常(以及如何修复它)?

编辑:详细说明我为什么要做我正在做的事情:微软提供了一个项目,该项目展示了如何将 OpenCV (C++) 集成到基于 HoloLens 的项目中。虽然它提供了一个混合了 OpenCV 和 C# 的 UWP 项目,但它没有展示如何将这个特定项目集成到 Unity 中。实际上有人通过 I2CPP 使这成为可能。虽然我在使用他的基于 Visual Studio 2017 的项目进入 Visual Studio 2019 时遇到了问题,但我尝试制作一个最小的示例来了解它(基本上)是如何工作的。

标签: c#c++unity3d

解决方案


我认为您误解了 IL2CPP 的概念。

IL2CPP (Intermediate Language To C++) 是 Unity 开发的脚本后端,您可以在为各种平台构建项目时将其用作 Mono 的替代方案。使用 IL2CPP 构建项目时, Unity 将 IL 代码从脚本和程序集转换为 C++,然后为您选择的平台创建本机二进制文件(例如.exe、apk、.xap)。IL2CPP 的一些用途包括提高 Unity 项目的性能、安全性和平台兼容性。

要使用 C++,您必须编写一个Native Plugin


推荐阅读