Search Unity

Мы не планируем прекращать поддержку и развитие IL2CPP, но мы подумали, что было бы неплохо сделать шаг в сторону и рассказать немного о том, как работает IL2CPP. В течение следующих нескольких месяцев мы планируем написать о следующих темах (возможно. и о других) в серии постов об IL2CPP:

Основы — набор инструментов и аргументы командной строки (этот пост).

  1. Экскурсия по генерируемому коду.
  2. Советы по отладке генерируемого кода.
  3. Вызовы методов (обычные методы, виртуальные методы, и т.д.).
  4. Реализация общего обмена.
  5. Обертки P/вызова для типов и методов.
  6. Интеграция сборщика мусора.
  7. Тестирование и применение фреймворков.

Мы собираемся обсудить некоторые детали о реализации IL2CPP, что, несомненно, изменится в будущем. Надеюсь, мы все еще можем предоставить некоторую полезную и интересную информацию.

Что такое IL2CPP?

Технология, которую мы называем IL2CPP, состоит из двух отдельных частей:

  • Ahead-of-time (AOT) компилятор
  • Исполняемая библиотека для поддержки виртуальной машины

AOT компилятор переводит промежуточный язык (IL) из .NET компиляторов в C++ код. Исполняемая библиотека предоставляет инструменты, такие как сборщик мусора, независимый от платформы доступ к потокам и файлам, реализации внутренних вызовов (нативный код, который изменяет управляемые структуры данных напрямую).

AOT компилятор

AOT компилятор IL2CPP называется il2cpp.exe. В Windows вы можете найти его в директории Editor\Data\il2cpp. На OSX – в директории Contents/Frameworks/il2cpp/build в месте установки Unity. Утилита Il2cpp.exe полностью написана на C#. Мы скомпилировали ее с помощью .NET и Mono компиляторов во время разработки IL2CPP.

Утилита Il2cpp.exe принимает управляемые сборки, собранные с компилятором Mono, который поставляется с Unity, и генерирует C++ код, который мы передаем в C++ компилятор конкретной платформы.

Вы можете думать об инструментах IL2CPP так:

il2cpp toolchain smaller

Исполняемая библиотека

Другая часть технологии IL2CPP — это исполняемая библиотека для поддержки виртуальной машины. Мы написали эту библиотеку почти полностью на C++ (он содержит немного платформенного кода, но пусть это останется между нами). Мы назвали ее libil2cpp, она поставляется в статической библиотеке связанной с исполняемым файлом плеера. Одно из ключевых преимуществ технологии IL2CPP — это простая и портативная исполняемая библиотека.

Вы можете найти некоторые подсказки о том, как код libil2cpp организован глядя на файлы заголовков для libil2cpp, которые поставляются с Unity (вы найдете их в директории Editor\Data\PlaybackEngines\webglsupport\BuildTools\Libraries\libil2cpp\include на Windows, или в Contents/Frameworks/il2cpp/libil2cpp на OSX). Например, интерфейс между генерацией C++ кода il2cpp.exe и libil2cpp находится в файле заголовка codegen/il2cpp-codegen.h.

Один из ключевых элементов — сборщик мусора. Мы поставляем Unity 5 с libgc, сборщиком мусора Boehm-Demers-Weiser. Тем не менее, libil2cpp была разработана, чтобы позволить нам использовать другие сборщики мусора. Например, мы исследуем интеграцию Microsoft GC, который стал с открытым кодом в рамках CoreCLR. Мы расскажем больше об этом позже в нашей статье об интеграции сборщика мусора.

Как выполняется il2cpp.exe?

Давайте рассмотрим на примере. Я буду использовать Unity 5.0.1 на Windows, и я начну с нового проекта. Так что у нас есть один пользовательский скрипт, я добавлю этот простой компонент MonoBehaviour к главной камере в сцене:

[csharp]using UnityEngine;

public class HelloWorld : MonoBehaviour {
void Start () {
Debug.Log("Hello, IL2CPP!");
}
}[/csharp]

Когда я соберу проект для WebGL, я могу использовать Process Explorer, чтобы увидеть команду Unity, используемую для запуска il2cpp.exe:

Это строка довольно длинная и страшная, так что давайте разберем ее. Во-первых, Unity запускает этот исполняемый файл:

Следующий аргумент — сама утилита il2cpp.exe.

Остальные аргументы передаются il2cpp.exe, а не mono.exe. Давайте посмотрим на них. Во-первых, Unity передает пять флагов il2cpp.exe:

  • —copy-level=None
    • Указывает, что il2cpp.exe не следует выполнять специальные копии файлов генерируемого C++ кода.
  • —enable-generic-sharing
    • Функция уменьшения размера кода и бинарника. IL2CPP поделятся реализацией генерированных методов, когда это возможно.
  • —enable-unity-event-support
    • Специальная поддержка кода для событий Unity, доступ к которым осуществляется с помощью рефлексии.
  • —output-format=Compact
    • Создание C++ кода в формате, который требует меньше символов для имен типов и методов. Этот код трудно отлаживать, поскольку имена в коде IL не сохраняются, но часто компилируется быстрее, так как будет меньше кода для разбора компилятором C++.
  • —extra-types.file=»C:\Program Files\Unity\Editor\Data\il2cpp\il2cpp_default_extra_types.txt»
    • Использует значение по умолчанию (или пустой) дополнительный файл типов. Этот файл может быть добавлен в проект Unity, чтобы знать, какие il2cpp.exe типы будут созданы во время выполнения, но не присутствуют в коде IL.

Важно отметить, что эти аргументы могут быть и будут изменены в более поздних версиях. Ещё не то время, когда у нас есть стабильный и поддерживаемый набор аргументов для il2cpp.exe.

В итоге у нас есть два файла и одна директория:

  • «C:\Users\Josh Peterson\Documents\IL2CPP Blog Example\Temp\StagingArea\Data\Managed\Assembly-CSharp.dll»
  • «C:\Users\Josh Peterson\Documents\IL2CPP Blog Example\Temp\StagingArea\Data\Managed\UnityEngine.UI.dll»
  • «C:\Users\Josh Peterson\Documents\IL2CPP Blog Example\Temp\StagingArea\Data\il2cppOutput»

Утилита il2cpp.exe принимает список всех сборок IL, которые следует конвертировать. В нашем случае это сборка, содержащая мой простой скрипт MonoBehaviour, Assembly-CSharp.dll и UnityEngine.UI.dll. Обратите внимание, что здесь есть несколько явно недостающих сборок. Очевидно, что мой скрипт ссылается на UnityEngine.dll, и, по крайней мере необходима mscorlib.dll, и, возможно, другие сборки. Где они? На самом деле, il2cpp.exe определяет эти сборки внутри. Они могут быть упомянуты в командной строке, но это необязательно. Unity явно нужно указать только главные сборки (те, на которые не ссылаются другие сборки).

Последний аргумент в il2cpp.exe — каталог, где должны быть созданы файлы C++. Если вам интересно, посмотрите на сгенерированные файлы в этом каталоге, они будут предметом следующей статьи в этой серии. Прежде чем это сделать, вы, возможно, захотите выбрать опцию «Development Player» в настройках сборки WebGL. Это удалит аргумент –output-format=Compact и даст вам лучшие имена типов и методов в созданном C++ коде.

Попробуйте изменить различные параметры в Player Settings WebGL или iOS. Вы увидите различные аргументы, передаваемые il2cpp.exe включающие различные этапы генерации кода. Например, изменение опции «Enable Exceptions» в Player Settings WebGL на «Full» добавляет аргументы –emit-null-checks, –enable-stacktrace, и –enable-array-bounds-check к вызову il2cpp.exe.

Чего не делает IL2CPP?

Я хотел бы указать на одну из проблем, которые мы не учли в IL2CPP. Мы не пытались переписать стандартную библиотеку C# в IL2CPP. При создании проекта Unity, который использует IL2CPP, весь код стандартных библиотек C# mscorlib.dll, System.dll и т.д. является точно таким же кодом, какой используется для написания скриптов с Mono.

Мы полагаемся на код стандартных библиотек C#, который уже известен пользователям и хорошо проверен в проектах Unity. Поэтому, когда мы исследуем ошибки, связанные с IL2CPP, мы можем быть достаточно уверены, что это ошибка в компиляторе AOT или в исполняемой библиотеки, и нигде больше.

Как мы разрабатываем, тестируем и выпускаем IL2CPP

С момента первоначального публичного релиза IL2CPP в версии 4.6.1p5 в январе, мы выпустили 6 полных релизов и 7 патчей (в разных версиях Unity 4.6 и 5.0). Мы исправили более 100 ошибок, упомянутых в примечаниях к выпуску.

Для того чтобы сделать это процесс совершенствования непрерывным, мы разрабатываем только одну версию кода IL2CPP. Перед каждым выпуском мы портируем изменения IL2CPP для конкретной ветки версий, запускаем наши тесты и проверяем, все ли исправления корректно работают в этой версии. Наши команды QA и Sustained Engineering проделали невероятную работу, чтобы сделать возможным выпуск обновлений так быстро. Это означает, что наши пользователи будут ждать не более одной недели с момента последних исправлений для IL2CPP.

Наше сообщество пользователей, оказалось бесценным, представив множество полезных сообщений об ошибках. Мы ценим все отзывы от наших пользователей, помогающие непрерывно улучшать IL2CPP, и мы с нетерпением ждем больше.

Команда разработчиков работает над IL2CPP имея настрой на сильный тест. Мы часто используем методы Test Driven Design, и редко отправляем запросы на слияние без хороших тестов. Эта стратегия хорошо работает для технологий, таких как IL2CPP, где у нас есть четкие входы и выходы. Это означает, что подавляющее большинство ошибок, которые мы видим, не неожиданное поведение, а неожиданные случаи (например, можно использовать 64-битный IntPtr как 32-битный индекс массива, в результате чего вылет с ошибкой компилятора С++, и в реальном коде на самом деле так делают!). Это различие позволяет нам быстро исправлять ошибки.

С помощью нашего сообщества мы работаем над тем, чтобы IL2CPP работал стабильно и быстро, насколько возможно. Кстати, если это интересно вам, у нас есть вакансия (просто говорю).

Дальше — больше

Боюсь, что я провел слишком много времени здесь, говоря о будущих записях в блоге. Нам многое хочется рассказать, и все это просто не уместятся в одном посте. В следующий раз мы будем копаться в коде, созданном il2cpp.exe, чтобы узнать, как ваш проект на самом деле выглядит для компилятора C++.

Комментарии закрыты.

  1. Well…moving to IL2CPP is not a great success for me…

    mscorlib_System_Predicate -> unknown class when building on xCode.

    Any idea what could be causing this problem?

    1. And it is in the Managed folder.

    2. I can’t say what the cause of the problem is from this error. Please try the latest patch release (if you have not already), as we are fixing bugs each week. If the problem still occurs, please submit a bug report with a project to reproduce the issue. That will help us to correct it. Thanks!

      1. It actually started to work magically??!! I added the dll manually to plugin folder, unity complained that there were now two of them, i removed and tadaa…
        i also added the latest patch after that just to make sure.

        Well three days of trials and failed attempts fixed on wrong move. That’s proper bug fixing I say.

  2. when i change to the IL2CPP , and i build the arm7 and arm64 arch , the build size is add 50M…what’s happen?? how can i debug this? can anyone help me ??

    1. The binary will be much larger, since it now has both architecture slices inside. For the initial IL2CPP releases, the IL2CPP binary was larger than the Mono binary even for the armv7 slice. In recent releases though, we’ve made the binary nearly as small, or smaller than Mono in some cases. So please try the latest patch release if you have not already.

      We’re working on more binary size improvements as well now, so expect that the size will decrease in future releases.

      1. thanks to the replay.
        I have another question about «nimt-trampolines » ,
        i add the «nimt-trampolines=8096» to the unity3D build setting,
        will it increase binary size ? or increase memory size ??

        1. The IL2CPP scripting backend does not use trampolines, so this setting is ignored, and will have no impact.

  3. Hi, can you please help me understand how IL2CPP affect use of generics? I’m still getting lost to understand it. Based on what I read is that generics and reflection works in C# thanks to JIT compiler on vanila .NET platform. Now IL2CPP will use AOT which means the use of generics should be affected. Will there be some article about how to use generics and reflection properly in order to be used with IL2CPP. This looks strange to me (I’m probably not getting this right), but doesn’t support of AOT cut off some C# language features?

    Second thing, you mentioned that Unity 5 is shipped with Boehm-Demers-Weiser garbage collector. Is this garbage collector used as main garbage collector and this is complete replacement for old Mono GC? If so, is this finally multigenerational GC? Is there any materials explaining how this GC works (I’ve found only github links to source code) and how to properly write C# code for this GC in order of getting better performance?

    Thanks for your reply :)

    1. IL2CPP should not have any impact on generics or reflection which is different from the Mono scripting backend for iOS now.

      Since iOS is already an AOT platform, nothing should change between the Mono and IL2CPP scripting backends. Anything that is different (and does not work for IL2CPP), is considered a bug, and we will correct it. So you can find documentation about Unity with iOS here:

      http://docs.unity3d.com/Manual/iphone-GettingStarted.html

      For AOT vs. JIT in general, AOT prevents the use of anything in System.Relfection.Emit, but most everything else in System.Reflection should work. Using reflection with generics where the generic arguments are value types can be a problem for AOT, but those cases don’t occur too often. We have a blog post about generic sharing coming soon which will tangentially touch on this.

      On the GC issue, the Boehm-Demers-Weiser garbage collector is used for IL2CPP on both 4.6 and 5.0. It does replace the Mono GC, but this is effectively the same GC used for Mono in Unity before. We’re using a newer version of the source code for the GC, but it still has the same features and behaviors. So I don’t think there is much you can do from the C# level to improve GC performance.

      We are investigating the use of the Microsoft GC that is a part of the CoreCLR, but we don’t have anything ready on that front yet. We’ll also have a blog post in this series about the GC coming up soon.

  4. Thanks for the Good Post.

    I understood that il2cpp.exe perform roles AOT compiler and runtime Library to support VM and also one role of runtime is the garbage collector.
    but I don’t know where IL2CPP VM is and what its role is.

    Could you tell me about that?

    1. Sure, the il2cpp.exe is really just the AOT compiler. It converts .NET IL code to C++ code. IL2CPP doesn’t really provide a full VM, at least for the strict definition of a VM. We are really still using the .NET VM, implemented by Mono.

      Instead, IL2CPP provides a static library named libil2cpp (on some platforms like iOS, libil2cpp is linked into another static library with other code). The libil2cpp library provides support functions for the .NET VM, like internal calls. Internal calls are native methods called by the C# managed code in mscorlib.dll and other standard library assemblies. It also provides garbage collector support, and access to platform specific resources via a common API.

      I hope this helps to clear things up a bit.

  5. what’s about IL2CPP support for Android and Windows Phone, is it coming any time soon?

    1. We’re working on some other platform ports of IL2CPP now. I can’t yet say which ones or when they will be ready though. We’ll announce them as soon as we can!

  6. Can you tell us about the advantages of Mono over CoreCLR. I’m just curious , honestly speaking I’m not involved with any WebGL or iOS project at the moment so am not affected by problems of early days of IL2CPP before getting mature.

    It seems CoreCLR should be the wise choice. Mono people will integrate more and more with it but will have their own version because of Xamarin and their mobile platforms and … Is there an advantage in following them instead of the faster more productive Microsoft team? Are you using some tech in Mon which is not available in CoreCLR which is not and will not be available on CoreCLR soon? Or it’s just a hard engineering problem to solve to switch?

    1. We’re using Mono for a number of reasons. Among them, Mono has been ported to many more platforms than CoreCLR (platforms where we need it), the cost of switching to CoreCLR does have a very high engineering cost (we can spend that time adding features or fixing existing bugs), and we’ve had good success with Mono in the past.

      We are very excited about where the .NET community is going though, and we’re looking forward to a bright future in the community, based on the move toward open source.

  7. Do you have any plan with SSE or NEON in IL2CPP ?
    Such as writing some special codes in C#, then IL2CPP will know these codes are using SSE or NEON.

    1. This is something we have considered. We don’t have any firm plans yet, but it is certainly a great opportunity to leverage our creation of a code generation tool to provide users with more power.

  8. Benoit Fouletier

    Май 7, 2015 в 2:50 пп

    I don’t understand this sentence: » We did not attempt to re-write the C# standard library with IL2CPP.»
    What do you mean? That the standard assemblies are il2cpp’d like any other assembly? If so, does that happen every time or do you have some kind of preprocess cache? (I guess with stripping you’d still want to postprocess them every time anyway.)
    What was the alternative? re-write the standard libs in C++ from scratch?

    1. This means that we use the same mscorlib.dll, System.dll, etc. assemblies for both the Mono and the IL2CPP scripting backends. If one of these assemblies is used, it is converted from IL to C++ via il2cpp.exe during each build.

      This conversion of the standard library code does increase both the conversion time in il2cpp.exe and the compile time for the native compiler. However, as you correctly point out, we need to convert each time the project is built because stripping can change the contents of these assemblies. We’re looking at ways to enable incremental builds and avoid converting these assemblies each time, but we’re not ready to release anything yet.

      The alternatives would be to re-write the standard libraries in each C# (and convert them) or write them in C++ with a thin C# wrapper. Neither option made much sense, as the approach we took allows us to leverage plenty of well-written, existing code.

  9. In one of the previous blog posts about IL2CPP I’ve read that eventually, Unity will switch from .NET 2.0 to a more recent version. Considering that the most recent version is 4.5.2, it seems only appropriate. Is this still on the roadmap?

    (Note: of course, what Unity really uses is Mono, but I don’t know which version of Mono corresponds to which version of .NET, and Unity states «Full .NET 2.0» in the editor, so I decided to stick with that)

    1. Yes, an upgrade to the latest version of Mono is on the roadmap. We don’t have dates or releases to talk about yet, but it is coming.

      1. Does it follow then that the Unity version of MonoDevelop will also get an upgrade?

        1. Yes, we’re also working on improvements to our interaction with MonoDevelop and hopefully an upgrade. Again, I can’t give any specific dates yet though.

  10. I believe the main reason for this tech to appear were iOS and WebGL platforms, and I don’t see any reasons it should be used on PC/Mac.

    1. You are correct that the original platforms for IL2CPP are WebGL and iOS. However, has been implemented to be more generally available. It might make sense on PC or Mac for certain cases, as it can provide better performance, for example. Not that IL2CPP is AOT-only, and does not provide a JIT. So existing projects which use features like System.Reflection.Emit (which is available on PC and Mac) won’t work with IL2CPP.

      In any case, we don’t have the PC or Mac platforms ready with IL2CPP now, although we are considering them for the future.

  11. It amuses me that .js scripts being built to webgl now follow the following transform:

    Javascript -> IL -> C++ -> LLVM bitcode -> Javascript

    1. Yes, this is a bit odd :) Remember though that «JavaScript» used in Unity really isn’t JavaScript. It’s UnityScript, which looks a lot like JavaScript, but compiles down to IL and runs on the Mono VM.

  12. Thanks for the insights. I see this is a interesting exercise from engineering point of view, and these’s the kind of hardcore work I loved to do at nights.

    From a business point of view however and for web publishing, this is still no a solution for any serious project and it seems far from ready, so I’m, with great interest (there’s money on the air!), looking after a breakthrough and usable achievement in the future.

    As others have stated if this technology can’t produce reduced sizes builds in a sensible time of our code similar to what a WebPlayer build means today (ok, not counting the Unity core runtime itself), then it can be shelved as a nice experiment or treat as an alpha.

    For me, web and Javascript mean near-instant usage during the lifecycle:

    — I don’t want to wait for +10 minutes each time I change a single line of code to test that on the web. Incremental builds?

    — I don’t want to see other pure WebGL or javascript applications start running in 2-3 seconds in modern devices, while having mine to wait for several minutes to load.

    So, honestly I think that before continuing the arguments around the number of fixes worked out, we need to know what are your assumed expectations for this technology (for this year), as IL2CPP + WebGL are being touted by you as a replacement for WebPlayer:

    I look forward to your next posts to learn more about:

    — What are the comparison performance magnitudes between WebPlayer and WebGL for same project? In size and build times (x2, x3, x5?).

    — What are the minimum sizes for a WebGL build compared with WebPlayer?

    — What kind of asset or code additions impact the most the build size of a WebGL project?

    — A known list of limitations or issues for WebGL builds (WWW? no substances? audio loops?).

    — Cloud builds for WebGL, when?

    — Any talks with Facebook for canvas applications on WebGL?

    Thanks very much.

    1. Most of your questions are not related to IL2CPP at all but rather on the WebGL itself and it’s limitations. I would not expect answers to platfrom specific issues but maybe for the common ones that are shared on all (like build time and size).

      1. You’re right, but correct me please if I’m wrong… what’s the point of IL2CPP from user point of view? Performance? I’m not worried about that right now, you know, could be, but we have a major show-stopper on the web, and the alternative seems to be WebGL. And… WebGL requires compiling with IL2CPP right?

        So I really don’t want to focus on a specific piece of the stack required behind a WebGL production, but on the overall experience. As a developer I care about platform specifics! If there’re limitations to WebGL itself, then we need to know as well! It could be misleading to think that as soon as IL2CPP is mature, then we’ll be able to work productively for the web!

        1. From the perspective of a Unity user, IL2CPP provides at least three benefits:

          1. Near native code performance for script code.
          2. Easier porting to new platforms, so Unity users should get new platform support sooner.
          3. Support for modern C#/Mono versions coming in the future.

          You are correct in saying that IL2CPP is required for WebGL. And WebGL does have some platform limitations outside the scope of IL2CPP (e.g. no support for threads).

          We’ve already seen some nice improvements in WebGL technology, and I expect those to continue, so I think the future for web publishing is bright, but we still have work to do.

        2. Well still it seems you are more after a blog post about WebGL itself and not IL2CPP with your questions. I assume such blog post will come sometime in future from guys in that team (Ralph, Jonas(?)) and maybe when WebGL might be moving out from preview state. In the mean time most of questions have been answered in the manual or in the WebGL forum section by devs.

    2. As mentioned in the blog post linked form this one about the future of web publishing, we do see WebGL as a key technology move forward. The question raised here are good ones. This blog post series is focused a bit lower in the technology stack, so I was not planning to address them. I’ll talk with our WebGL team to see if we can address these questions though.

    3. Jonas Echterhoff

      Май 7, 2015 в 2:30 пп

      As stated before, your questions are mostly specific to the WebGL platform, and not il2cpp, what this blog post is about. I plan to write a blog post on the status and plans for WebGL within the next month or so, stay tuned for that. But I’ll try to answer your questions quickly:

      – What are the comparison performance magnitudes between WebPlayer and WebGL for same project? In size and build times (x2, x3, x5?).

      This depends on a lot of factors (browser used, subsystems used).
      See here for a more in-depth analysis:
      http://blogs.unity3d.com/2014/10/07/benchmarking-unity-performance-in-webgl/

      – What are the minimum sizes for a WebGL build compared with WebPlayer?

      Currently, minimal projects in Unity WebGL weigh in at about 3 MB total download size. I hope to get that down to below 2 in the future. For the web player, a minimal project is just a few KB, but bear in mind that that does not include the engine code itself, which adds a 10 MB download to the web player every time it needs a new engine version.

      – What kind of asset or code additions impact the most the build size of a WebGL project?

      It’s hard to give a general answer to this. But any subsystem touched in Unity will add to the build size. PhysX, for instance is a big one — if you don’t use any Colliders/Rigidbodies/Raycasts/etc, your build will shrink significantly. Third party .NET dlls also frequently add a lot to your build sizes.

      – A known list of limitations or issues for WebGL builds (WWW? no substances? audio loops?).

      See the list here: http://docs.unity3d.com/Manual/webgl-gettingstarted.html
      FYI, Audio Loops will work in WebGL in 5.1.

      – Cloud builds for WebGL, when?

      Can’t tell, not on the cloud build team.

      – Any talks with Facebook for canvas applications on WebGL?

      Yes.

      1. To Jonas and Joshua, thank you very much for your answers. I have read some comments on WebGL platform forum and I’m really excited to test those improvements!

      2. Thank you Jonas!

        It’s really nice to see you’re in talks with Facebook. I’m excited to see what you both can provide together, in terms of Facebook Canvas but with WebGL.

        In addition to Facebook API, I hope they also update their Parse API to support WebGL because it really works very well with current Unity WebPlayer platform.

  13. alexander blanco

    Май 7, 2015 в 7:05 дп

    Emscripten is an amazing tool. Im looking forward to see more of unity on the web. Alon Zakai seems to be on board. I saw him tweet the Unity Teleporter demo on WebGL not too long ago.

  14. With all the time and money spend in IL2CPP and the only little results you obtained so far, how confident are you about the future of IL2CPP. I mean how much time more do you need before realizing that this was an overly ambitious project that has only delivered broken promises. Every body want a better mono, when are you going to try to do what people really need…

    1. I wouldn’t say they haven’t gotten results. What they’ve done so far is impressive and working for a lot of people. They couldn’t get acceptable terms for licensing updated mono for mobile. So either they’d have to use different mono versions for desktop vs mobile (a bad idea) or move to something else. By moving mobile over, that frees them up to update mono on desktop systems to a more recent version, or possibly even move over to Microsoft’s .NET now that it’s opened up. And eventually we could see an option to build via IL2CPP for desktop platforms as well, if there’s performance gains to be seen there and you don’t need support for the unsupported runtime stuff.

      I for one am happy that you guys went this direction, keep up the good work. Looking forward to seeing the performance increases made possible by this (either directly or indirectly by enabling us to use more recent runtimes).

    2. Thanks for your concern here, I think that this an important question. If it is true (as we have been saying), that IL2CPP is a big part of the future of scripting in Unity (and it is), then we need to be confident that it will be solid.

      I wouldn’t say that we have been overly ambitious or broken promises. Certainly, IL2CPP is not quite where we want it to be yet, but it is getting there — fast. Many customer are shipping significant games using IL2CPP technology now, and we’re seeing more every day.

      The key things that gives me confidence in IL2CPP is our iteration rate. We’ve made some technology decisions with IL2CPP (e.g. writing the code conversion in C#, keeping the runtime library simple and cross-platform, re-using the existing class libraries) which have allowed us to move quickly. By continually improving IL2CPP, we’re moving fast toward the place where we want to be.

  15. Arnaud Couturier

    Май 6, 2015 в 11:48 пп

    Very informative and interesting post! Waiting for the others.

  16. Thanks, i’ve pretty much understood the compilation process even before reading this post (but it was nice to get to know a few of those command line args).

    With regards to debugging — is it even possible to debug the game once it was transformed to c++ ? having looked at it a few times, it does not resemble the original code in any way.

    1. Yes, it is possible to debug the generated code (for example, on iOS using Xcode). Although it is not always easy. Since the C++ code is generated from IL, not C#, you’re really debugging something like IL code. So you need to make the mental jump from C# to IL, then debug IL code. I’ve been surprised more than once about how the C# code looks in IL!

      The next post in this series attempts to demystify that a bit, looking at the layout of generated code and a few common cases. The third post attempts to use that information about the generated code to help debugging it in Xcode.

  17. O unity eo maximo

  18. Nicholas Ventimiglia

    Май 6, 2015 в 7:45 пп

    Will this solve any of the cross platform issues ? For instance : No events within dlls on iOS, limited generics on iOS (trampolines), no threading on WebGL. Moreover, will this add support for newer dotnet features such as TPL and async operators.

    1. Some yes, and some no.

      > No events within dlls on iOS — no IL2CPP doesn’t change anything here.

      > Limited generics on iOS (trampolines) — Yes, IL2CPP doesn’t use trampolines, so has no such restriction

      > No threading on WebGL — no , IL2CPP does not help here. Once browsers support threads in WebGL, then we can implement them in IL2CPP.

      > Will this add support for newer dotnet features such as TPL and async operators — Immediately, no. But as outlined in the post about the future of scripting in Unity, Il2CPP is the path to getting the newer C# features in Unity. We’re not there yet, but we plan to get there.

  19. Great job :)
    I’m looking forward to the next posts!

  20. Just a quick question. Now that U5 is up and out, do you have a deadline for U4 project developers? My project is U4 and due to serious shader and API changes in U5 it would take me up to 2 months to migrate, which will destroy deadlines. Meanwhile as I’m getting closer to release, I’m getting more and more nervous since I’m planning to ship fixes and updates and it would be painful to find out when Unity team suddenly (well, hopefully not!) decides to drop U4 support a couple weeks after the release of my U4 project.

    How long do we, Unity 4 project developers have really? I don’t need a specific EOL date, just an approximation, please.

    1. I’m not sure if or when support for U4 will end (the decision is not mine). I expect that it will be clearly communicated though, and well in advance. I can say that as long as U4 is supported, we will continue to port the latest IL2CPP code to U4.

      1. Thank you.

    2. We plan to continue releasing 4.6 patch releases at least until the end of 2015, though they’ll get less frequent than the current weekly schedule, and the fixes will be increasingly limited to only the most critical issues.

  21. When you showed us that code snippet above. I thought you’d step through the various outputs (ie C#->IL->C++). I mean it’s cool that you took your time to outline the steps involved. But that snippet isn’t very useful to the understanding of this post unless we’re able to follow it’s journey from C# to C++. My thoughts.

    1. We’ll see that a bit in the next blog post, exploring the generated code. There we’ll see how the C# code looks in C++ (although not in IL). That post should be up next week.

  22. «Are there plans to move to .NET Core instead of Mono?» — I really don’t understand why they don’t focus their time on that. IL2CPP has been a complete disaster for me and my team. We have missed iOS launches and deadlines for ~3-4 months now.

    -It takes literally takes more than 10 minutes to compile.

    -The build size is massive….EVEN FOR A PRACTICALLY EMPTY PROJECT.

    -There are still bugs…Still. Yes the dev team is doing a great job at fixing them. But at this rate we are going to see this kind of crap every time apple updates their iOS. Plus I can’t imagine actually being able to support later versions of .net.

    Two better approaches would be to:

    1: Use mono 64 bit now that it has been released for iOS.
    2: Use the real .net — as of last week Microsoft just released .net on all platforms. (including mac and linux)

    1. Our top development priority is now executable size. We’ve delivered some improvements in recent releases, and we have more coming, so stay tuned. We’re also aware that build times are far too long. We’re working on that as well. So you’ve hit on a couple of the biggest problems with IL2CPP now, but we are working to fix them.

      Looking further ahead, we don’t anticipate any serious problems with new iOS versions. Since IL2CPP is generating cross-platform C++ code, we have confidence that we can quickly deal with changes in the future.

      With that said, I feel for the delays you’ve had with our team — they clearly not acceptable. If you have any outstanding bugs that we should check on, let me know and I’ll have a look at their current status. Thanks.

  23. Only haskell, my dears

  24. When do you plan to port il2cpp to Windows, Mac and Linux? Also what about the latest C# standard?

    1. We have some more IL2CPP platforms in development now, but that is the best I can tell you, unfortunately. We’ll have releases and dates available as soon as we are ready for new platforms.

      We’re in the same boat for the C# upgrade. It is something that we want to do, but we’re not ready to point to a specific date or release yet.

    2. Why do you need that at all?

  25. Are there plans to move to .NET Core instead of Mono?

    1. No, we have no plans now to switch away from Mono. We are still on track to upgrade to a newer version of Mono, as outlined in the earlier blog post about the future of scripting in Unity (although we don’t have specific releases or dates ready to discuss).

      With that said, we’re very excited about where the .NET community is going, especially with respect to open source code.

      1. I don’t really understand why we should be stuck in the stone age that is Mono as .Net Core should generate the same bytecode. Hopefully when the new .Net Core open source community matures it’ll blow xamarin right the hell out of business.

        1. When you showed us that code snippet above. I thought you’d step through the various outputs (ie C#->IL->C++). I mean it’s cool that you took your time to outline the steps involved. But that snippet isn’t very useful to the understanding of this post unless we’re able to follow it’s journey from C# to C++. My thoughts.

      2. Do you know if there are any plans to switch the compiler to Roslyn for generating the IL? It can compile for .net 3.5 and would mean we could make use of all the C# 6 language features that .net 3.5 support.

        1. We have no plans to switch to Roslyn now.