Search Unity

[Official] The collected il2cpp forum topic.

Discussion in 'General Discussion' started by RalphH, May 20, 2014.

  1. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    Pretty sure? or verified? By default with a new Unity project built to XCode with IL2CPP pressing the Play button (in XCode) or doing a Build and Run from Unity will be in Debug mode (not release mode). (someone please correct me if I'm wrong)

    Unless you explicitly change something yourself.

    Edit: Note doing an archive build (from XCode) should be in release mode by default though.
     
  2. Schubkraft

    Schubkraft

    Unity Technologies

    Joined:
    Dec 3, 2012
    Posts:
    1,073
  3. imaginaryhuman

    imaginaryhuman

    Joined:
    Mar 21, 2010
    Posts:
    5,834
    maybe it was asked already.... when will we see il2cpp/faster script speeds on Mac/Windows standalone?
     
  4. Schubkraft

    Schubkraft

    Unity Technologies

    Joined:
    Dec 3, 2012
    Posts:
    1,073
    As mentioned we are going to bring IL2CCP to all the platforms where we can't upgrade the Mono runtime (mostly consoles) and then we can upgrade the Mono runtime for editor and standalones. This should see some nice improvements too. So sadly it is going to be a while still.
     
  5. tonydongyiqi1

    tonydongyiqi1

    Joined:
    Jun 30, 2015
    Posts:
    13
  6. -Aymeric-

    -Aymeric-

    Joined:
    Oct 21, 2014
    Posts:
    110
    It seems there are still some issues with some .dll libraries. Submitted a bug with EAGetMail.dll doesn't work with IL2CPP on iOS (Xcode compilation crashed) but works fine with Mono2x.
     
  7. tonydongyiqi1

    tonydongyiqi1

    Joined:
    Jun 30, 2015
    Posts:
    13
    I was testing the performance of Get Set property with Field Access.
    Found IL2CPP mode,access the class member cost almost 8 times than Mono.
    I've upload the Test Script here~
     

    Attached Files:

  8. tonydongyiqi1

    tonydongyiqi1

    Joined:
    Jun 30, 2015
    Posts:
    13
    and I found the way handle LOOP in IL2CPP is the point! here's the code in .cpp gernerated by unity.
    IL_002e:
    {
    SetGetClass_t43 * L_6 = (__this->___setgetObj_4);
    NullCheck(L_6);
    int32_t L_7 = SetGetClass_get_PropGetSet_m107(L_6, /*hidden argument*/&SetGetClass_get_PropGetSet_m107_MethodInfo);
    V_3 = L_7;
    int32_t L_8 = V_2;
    V_2 = ((int32_t)((int32_t)L_8+(int32_t)1));
    }

    IL_003e:
    {
    int32_t L_9 = V_2;
    IL2CPP_RUNTIME_CLASS_INIT(InitializedTypeInfo(&TestGetSet_t45_il2cpp_TypeInfo));
    int32_t L_10 = ((TestGetSet_t45_StaticFields*)InitializedTypeInfo(&TestGetSet_t45_il2cpp_TypeInfo)->static_fields)->____nLoopCount_9;
    if ((((int32_t)L_9) < ((int32_t)L_10)))
    {
    goto IL_002e;
    }
    }

    and functiones :

    IL2CPP_RUNTIME_CLASS_INIT(InitializedTypeInfo(&TestGetSet_t45_il2cpp_TypeInfo));
    int32_t L_10 = ((TestGetSet_t45_StaticFields*)InitializedTypeInfo(&TestGetSet_t45_il2cpp_TypeInfo)->static_fields)->____nLoopCount_9;

    cost a lot of time~ . It called in each loop. Please fix it ~
    thank you ~
     
  9. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    Using Unity 4.6.7f1 and 4.6.6p3.

    I'm experiencing a deallocation exception in some IL2CPP code.

    C# code:
    Code (csharp):
    1.         //
    2.         // DLL import declaration.
    3.         //
    4.         [DllImport ("__Internal")]
    5.         private static extern string _currentUserDisplayName();
    6.  
    7.         //
    8.         // The invoked method which just calls the import.
    9.         //
    10.         public static string CurrentUserDisplayName
    11.         {
    12.             get { return _currentUserDisplayName(); }
    13.         }
    Generates the following C++:

    Code (csharp):
    1. extern "C" String_t* Zzz_currentUserDisplayName_m1043 (Object_t * __this /* static, unused */, const MethodInfo* method)
    2. {
    3.     {
    4.         String_t* L_0 = Api_get_CurrentUserDisplayName_m801(NULL /*static, unused*/, /*hidden argument*/NULL);
    5.         return L_0;
    6.     }
    7. }
    8.  
    9. extern "C" String_t* Api_get_CurrentUserDisplayName_m801 (Object_t * __this /* static, unused */, const MethodInfo* method)
    10. {
    11.     {
    12.         String_t* L_0 = Api__currentUserDisplayName_m789(NULL /*static, unused*/, /*hidden argument*/NULL);
    13.         return L_0;
    14.     }
    15. }
    16.  
    17. extern "C" {char* DEFAULT_CALL _currentUserDisplayName();}
    18. extern "C" String_t* Api__currentUserDisplayName_m789 (Object_t * __this /* static, unused */, const MethodInfo* method)
    19. {
    20.     typedef char* (DEFAULT_CALL *PInvokeFunc) ();
    21.     static PInvokeFunc _il2cpp_pinvoke_func;
    22.     if (!_il2cpp_pinvoke_func)
    23.     {
    24.         _il2cpp_pinvoke_func = (PInvokeFunc)_currentUserDisplayName;
    25.  
    26.         if (_il2cpp_pinvoke_func == NULL)
    27.         {
    28.             il2cpp_codegen_raise_exception(il2cpp_codegen_get_not_supported_exception("Unable to find method for p/invoke: '_currentUserDisplayName'"));
    29.         }
    30.     }
    31.  
    32.     // Native function invocation and marshaling of return value back from native representation
    33.     char* _return_value = _il2cpp_pinvoke_func();
    34.     String_t* __return_value_unmarshaled = { 0 };
    35.     __return_value_unmarshaled = il2cpp_codegen_marshal_string_result(_return_value);
    36.  
    37. //
    38. //  THE FOLLOWING LINE EXPLODES WITH THE ALLOCATION ERROR
    39. //
    40.     il2cpp_codegen_marshal_free(_return_value);
    41.     _return_value = NULL;
    42.  
    43.     return __return_value_unmarshaled;
    44. }
    il2cpp_codegen_marshal_free(_return_value) is exploding with the following exception:

    zzz(10802,0x3ab519dc) malloc: *** error for object 0x1a160379: pointer being freed was not allocated


    Thrown from:

    Code (csharp):
    1. inline void il2cpp_codegen_marshal_free(void* ptr)
    2. {
    3.     il2cpp::vm::PlatformInvoke::MarshalFree(ptr);
    4. }
    I've stepped through the code and the _return_value contains a sane string.

    Edit: Are there any guarantees about the allocation of the data returned from _il2cpp_pinvoke_func() ? It appears to assume that it's safe to call MarshalFree() on it...
     
    Last edited: Jul 3, 2015
  10. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    According to .NET PInvoke rules, the marshaller is supposed to free memory. On non Windows, this means ordinary free(), while on Windows it's going to be CoTaskMemFree().

    That also means that you have to allocate the memory using malloc on non-Windows platforms, and allocate using CoTaskMemAlloc on Windows.
     
  11. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    Ah right - this is a 3rd party SDK that's being called from Unity - is there anything that can be done without needing to get the third party to fix their SDK?
     
  12. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    There are couple of workarounds, depending on what you want to do. In either case, you'll need to find out how they're allocating the string.

    Easiest solution would be to change P/Invoke signature in C# to return IntPtr rather than string, and do the marshaling yourself.
     
  13. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    Excellent - thanks for the help.
     
  14. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    This worked perfectly, thanks.
     
  15. noethis

    noethis

    Joined:
    Nov 11, 2013
    Posts:
    129
    Anybody else experiencing performance issues / significantly longer load times with IL2CPP on iOS in the last week or two? I still have to track it down but I believe it was when I updated to 5.1.1p1 (from f1).
     
  16. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    @noethis: I don't think we're aware of it. Could we have a bug report?
     
  17. tonydongyiqi1

    tonydongyiqi1

    Joined:
    Jun 30, 2015
    Posts:
    13
  18. Jiraiyah

    Jiraiyah

    Joined:
    Mar 4, 2013
    Posts:
    175
    sigh i have read 11 pages of this forum post, each one of the posts and thought about each one for few minutes, i still wonder, why somethings happen
    1- why people bother to spam unity's forums about being able to code in c++ the way they do it with c# (scripting)
    2- why people are not reading 11 pages of forum post carefully to see what is going on. this forum is not that big compared to many forums you guys sit and read every post for 40 pages there lol because if you had read all the pages here, you would see that time and time developers mentioned very politely how stupid some people are when they say you should go for xamarin license, how should a developer answer that? the best was this "trust that we can do simple math !" also, those people would see that developers time and time said that mono even the latest built wouldn't be the best solution because lots of platforms Unity is supporting has no built in connection to mono and making that connection happen some times needed year !
    3- Why when we see something new, under development, many of us start crying loud and yell that this is bad blah blah, let me tell you my first thoughts when i saw few video tutorials on Unreal Engine, here is a brief list :
    • what the hell, i need to run the editor from inside visual studio time and time again when i do major changes in code?
    • what the hell are all these macros, why would anyone do such a stupid way of hooking to .net?
    • c++? no thank you, i don't need a 4th language to learn
    • who said this engine is the best when it comes to making games? not me !
    well, things on the same line with more bad mouthing lol, anyways, point is, one of the major and power anchor points of Unity is c# because it's easier, less head ache, and more productive. another part is how they try to make our life and even jobs easier by trying to minimize what is needed to be done to target more platforms, and, now with new licensing system, free for everyone on all the development aspects of the engine itself. Now what we see? some stupid guy comes and says HEY, people should buy xamarin license if they want to develop for ios, completely forgetting that many many developers are indie or small companies who just started in this sector and can't afford big money, but want to target more platforms to gain more money to stand on their feet sooner than later.
    You know, if you ask my opinion about macro system in unreal engine, i would yell, trash talk and god save your ears, but look at what Epic is doing, still continuing with it. compared to it, IL2CPP is much better system, well, not that they are comparable on technical aspect but what i want to say here is that when you see a new thing being developed, don't yell or cry like a baby, sit, read, think, you will see that it has great great potential as a NEW TECHNOLOGY. And if you think such a technology can be robust and developed under a year or two, then you should immediately leave this community, coding and game development ! Also, remember this, many of the technology we are using today on computers and different sectors of it, in their first years of development would look like a crazy idea. for many of you in this forum that think il2cpp is crazy and unity should have stop developing it, i suggest that you go and read the book about life of Steave Jobs (sorry if i spelled the name wrong). you would see how stupid you sounded when you were suggesting a company to rely on another one specially one that is money hungry with very bad shipment plans when it comes to business (aka xamarin)
    as last word, selfishness should have a limit !
     
    recursive likes this.
  19. Jiraiyah

    Jiraiyah

    Joined:
    Mar 4, 2013
    Posts:
    175
    Also, on a side note, something came into my mind that seems no one paid any attention to o_O, in latest unite i saw someone asking unity developers about visual coding system in unity, did you ever thought that when il2cpp get to it's stable releasing stage, it would be totally bad ass to use it for a visual coding system:cool:?
    lets take a look what we have now, an asset like play maker, in the shell is some scripts with editor stuff that generates codes blah blah
    now sit back, kick your legs on desk and start drinking coffee :) and think o_O, can we use much much simpler editor wizard and node connection system, to develop a full visual coding system using il2cpp :confused:? i think we should be able to (we as unity developers :confused:) that would make sense because il2cpp could look into the node and analyze the graph and generate the c++ code from it without user even touching the programming IDE. of course, if you have cells in brain and are serious about developing a good game, sooner or later you would need to sit and learn c#:rolleyes:, but still, having the ability to visual coding for non coders and artists would be nice, the point is, when il2cpp is there, the process should be much easier at low level and back end for unity devs to develop their own system without needing to hook to current api, scripting blah blah.
    oh well, i don't know if i was right or wrong there but devs can correct me if i was wrong but i think using il2cpp would be easier to write a simpler system to analyze the node tree and develop code compared to what we can do right now :D
     
    recursive likes this.
  20. bigdaddy

    bigdaddy

    Joined:
    May 24, 2011
    Posts:
    153
    I saw 2 questions here that haven't been answered so I thought I'd bump these questions:
    1. With IL2CPP the Stripping Level setting is by default "Strip byte code" even if its set to Disabled or Strip Assemblies, correct?
    2. Does Script Call Optimization have any effect on an IL2CPP build?
    Thanks!
     
    larku likes this.
  21. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    1. Managed code stripping is always enabled for IL2CPP builds.
    2. Is that the setting that causes Mono not work with exceptions? If so, that setting has no effect for IL2CPP (I think it's also iphone specific setting, right?).
     
    bigdaddy likes this.
  22. Deleted User

    Deleted User

    Guest

    It's Ironic, some of what you're saying puts you in the same category as the people you're insulting.

    1. From a technical perspective, the smart thing to do is to drop Java (well Unityscript), C# etc. all together and have everything C++ (No conversion overhead, no additional work to abstract per platform etc. etc.). From a business perspective, it would be the dumbest move ever. The almost brain dead component scripting system is one of the major reasons why Unity became successful in the first place. So it's logical, but not practical..

    2. Agreed, the limited interaction I've had with Mono wasn't pretty. From the supported platforms, compared to all the platforms unity supports http://www.mono-project.com/docs/about-mono/supported-platforms/ it probably isn't the best decision.

    3. No, but you can run the editor from inside VS if you choose to by compiling source and modifying. They don't hook to .net that's the whole point, you just learning languages for the sake of it? You only need to know C++. In Unity you only need to know C#. If you're talking Mono integration with UE, well that'd never be a good idea to start with.

    Xamarin licenses aren't that expensive, I'd be worried if I couldn't afford with UE $25.00 a month for a personal license. But Unity said they are upgrading major platforms anyway. So I'm not sure what the issue is? (In that Unity gives you it for nothing)..

    Personally as a developer, I think IL2CPP is a great idea. Cut some dependencies on Mono, gives complete access to the devs which helps in re-structures and allows them to upgrade Mono on supported platforms which would benefit from it.

    From a customers standpoint, don't really care what they do as long as it works well.
     
    Last edited by a moderator: Jul 28, 2015
  23. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    I think he was referring to requiring a Xamarin license to use .NET with UE, not Unity. :)
     
  24. Deleted User

    Deleted User

    Guest

    So was I :).. I did look into it and was going to get the "enterprise" license or whatever. Then just decided it REALLY isn't worth it.

    Edit: I explained further.
     
    Last edited by a moderator: Jul 28, 2015
    Dustin-Horne likes this.
  25. piacentini

    piacentini

    Joined:
    May 27, 2014
    Posts:
    28
    Not sure if this is the correct forum for sharing information about strange bugs/regressions in il2cpp, please correct me if there is a better place.
    This bug was reported here: http://fogbugz.unity3d.com/default.asp?716517_92is8qm64dj9l2uo
    As you can see, it is a regression that is preventing my game from moving from 5.02 to 5.1.x.
    The really strange part is that it works on all Mono versions, the editor (expected) but fails on iOS-il2cpp (no crashes or error messages, only incorrect behavior as shown in the bug report). However, it DOES work on WebGL, which also uses the il2cpp translation.
    As the Unity side of the code has not changed (and it still works on the Editor) it looks like some recent il2cpp fix is triggering this bug while translating the code, but ONLY for iOS. How different is il2cpp generation between WebGL and iOS, and does it give a clue about where to start looking for the bug?
     
  26. Yukichu

    Yukichu

    Joined:
    Apr 2, 2013
    Posts:
    420
    • (710153) IL2CPP: Correct a C++ compiler error in generated code: "No matching function for call to 'il2cpp_codegen_raise_exception'".
    I see this resolved in 4.6.7p2 and 5.2.0B4 (Beta) but not in 5.1.2p1 (different forum referenced it would be fixed then: http://forum.unity3d.com/threads/4-6-ios-64-bit-beta.290551/page-44#post-2203738 )

    Was it missed in the notes, or missed in the build, or have to wait for 5.2 Beta for resolution? Any information is appreciated.
     
  27. GXMark

    GXMark

    Joined:
    Oct 13, 2012
    Posts:
    514
    I have a question concerning IL2CPP support inside asset bundles. Currently if you want to add a script to an asset bundle you have to compile your c# as bytecode and add it to your bundle. Then on load you read the bytes and create your component from the bytecode. This works fine at the moment.

    Will IL2CPP allow this bytecode to be recreated as a component? Or will there be some other approach to achieve this? I hope that some approach has been considered since my projects relies on scripts inside bundles.

    Any thoughts?
     
  28. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    There is no way to bundle il2cpp generated code within an asset bundle, at least not at the moment. It is an AOT compiler as described e.g. here: http://blogs.unity3d.com/2015/05/06/an-introduction-to-ilcpp-internals/
    It would be required to develop another solution for the linking for each backend of il2cpp and still not all platforms would support it. If they have it in mind, I would bet that it has a very very low priority.
    I would be surprised to see it in the next three years and would not be surprised if it was never implemented.
     
    Ostwind likes this.
  29. GXMark

    GXMark

    Joined:
    Oct 13, 2012
    Posts:
    514
    So lets say you wanted to provide scriptable assets on a marketplace for your game. Thats not supported anymore! Seems like the RPG and MMO community for Unity will love that ! In fact that would relegate asset bundles in unity to purely data assets. Why do unity always tend to head down the build time rather than runtime support for games across all their tech. Or am i missing something here?
     
  30. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,657
    On iOS, and other AOT platforms, that was never supported, AFAIK. And even on platforms which aren't AOT, it has never been possible to, for example, ship a whole new MonoBehaviour in an AssetBundle.

    Provided the TOS for the platform you're targeting allow it, it's always possible for you to run a scripting engine on top of IL2CPP - I mean, for some games it's as simple as parsing a text file with a list of commands in.
     
  31. mdrotar

    mdrotar

    Joined:
    Aug 26, 2013
    Posts:
    377
    I've never tried it but doesn't http://docs.unity3d.com/Manual/scriptsinassetbundles.html show an example of loading a MonoBehaviour from an AssetBundle? ... as long at it's not an AOT platform, Windows Store app or Windows Phone app...
     
  32. r618

    r618

    Joined:
    Jan 19, 2009
    Posts:
    1,305
  33. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,657
    Well wouldja look at that. I'm kinda amazed that works, but OK then - my mistake :)
     
  34. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    The advantage of AOT is that more optimizations can be made. The drawback is that runtime support as you name it, is not anymore possible, or becomes more complex.

    Which platform do you have in mind?
     
  35. Fiction

    Fiction

    Joined:
    Sep 26, 2011
    Posts:
    5
    You are making it sound like IL2CPP is never coming for windows standalone. Can you please confirm this will happen before 2017?
    Mono lacks the required security.
     
  36. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    "It is going to be a while still" really doesn't mean "never". It means "a while". They won't confirm anything by specific dates when it's that far out. You can keep an eye on this: http://unity3d.com/unity/roadmap. IL2CPP won't make your code unhackable, though. If you really need security, the only option is to run your code on a server.

    --Eric
     
  37. Fiction

    Fiction

    Joined:
    Sep 26, 2011
    Posts:
    5
    Thanks for the response Eric.
    I know it was said earlier that it will come for standalones, but I just have to make sure after a reply like the one below.

    "IL2CCP to all the platforms where we can't upgrade the Mono runtime"

    So if I understand correctly IL2CPP for standalones is the step after "then we can upgrade the Mono runtime for editor and standalones."?

    I'm sure nobody is dreaming of unhackable code, but something that doesn't slow the code and is a bit harder to crack than dragging and dropping an exe file to a 3rd party program is always welcome.
     
    larku likes this.
  38. rchapman

    rchapman

    Joined:
    Feb 13, 2014
    Posts:
    105
    Why is this setting ignored? Managing a link.xml file to support serialization is a terrible solution.
     
  39. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    Last time we checked, disabling stripping makes builds become so large that they're practically unshippable. We might reevaluate at some point.
     
  40. mdrotar

    mdrotar

    Joined:
    Aug 26, 2013
    Posts:
    377
    The way obfuscation tools solve the same problem is to use attributes on classes. So for your case, if you want force something to not be stripped, add something like a [DoNotStrip] attribute to the class. The stripping process could then check for that attribute. After processing, the attribute itself can be stripped from the class. Sort of like generating a link.xml automatically. In addition, they also allow the developer to specify other attributes or class types to look for that indicated the class shouldn't be obfuscated/stripped such as [Serializable] or ISerializable.

    Something to consider, if you haven't already.
     
    Daniel-F and larku like this.
  41. tonydongyiqi1

    tonydongyiqi1

    Joined:
    Jun 30, 2015
    Posts:
    13
    hello Unity Techs...here's another bug or problem with IL2CPP.
    I need to change the value created from unity (such as position.x, position.y) in C++ code. I pass the ref value to C++ code. It works correct in Mono2.x build,but in IL2CPP build, the value can not be changed.
    I've reported bug with demo uploaded , url :http://fogbugz.unity3d.com/default.asp?735916_o51bccv9uvbc742v

    I checked the code , auto gernerated code shows you just the a temp float param(____x_marshaled_dereferenced) but not the real param address(___x) i pass.The Code il2cpp generated:

    float* ____x_marshaled = { 0 };
    float ____x_marshaled_dereferenced = { 0 };
    ____x_marshaled_dereferenced = *___x;
    ____x_marshaled = &____x_marshaled_dereferenced;

    // Marshaling of parameter '___y' to native representation
    float* ____y_marshaled = { 0 };
    float ____y_marshaled_dereferenced = { 0 };
    ____y_marshaled_dereferenced = *___y;
    ____y_marshaled = &____y_marshaled_dereferenced;

    // Marshaling of parameter '___fMass' to native representation

    // Marshaling of parameter '___collisionGroup' to native representation

    // Native function invocation and marshaling of return value back from native representation
    int32_t _return_value = _il2cpp_pinvoke_func(____fRadius_marshaled, ____x_marshaled, ____y_marshaled, ___fMass, ___collisionGroup);
     
  42. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    In managed code you have:

    Code (csharp):
    1. [DllImport("__Internal")]
    2. public static extern void AddPhysicObject_(ref float x, ref float y);
    3.  
    4. [DllImport("__Internal")]
    5. public static extern void Move(float fDeltaTime);
    6.  
    7. Vector3 vPos;
    8.  
    9. void Start ()
    10. {
    11.     AddPhysicObject_(ref vPos.x, ref vPos.y);
    12. }
    13.  
    14. void Update ()
    15. {
    16.     Move(Time.deltaTime);
    17.     transform.position = vPos;
    18. }
    In native code you have:
    Code (csharp):
    1. float* s_fX;
    2. float* s_fY;
    3. EXPORT_API void AddPhysicObject_(float* x, float *y)
    4. {
    5.     s_fX = x; s_fY = y;
    6. }
    7. EXPORT_API void Move(float fDeltaTime)
    8. {
    9.     *s_fX += fDeltaTime * 1;
    10.     *s_fY += fDeltaTime * 1;
    11. }
    In short... don't do this. It's a miracle it worked on Mono in the first place. You're Not allowed to retain pointer to a variable that lives in C# land. The validity of the pointer lasts until the end of AddPhysicObject_, and after that, the pointer becomes invalid, thus you invoke undefined behaviour since you're retaining the pointer in a global variable. If you want to modify the value like that, you'll have to pass its address every time you P/Invoke.

    In general, even if it worked like Mono, you'd crash as soon as the garbage collector decided to move the managed object to a different place.
     
  43. tonydongyiqi1

    tonydongyiqi1

    Joined:
    Jun 30, 2015
    Posts:
    13
    What if i pin the address of the variable using System.Runtime.InteropServices?
    I understand what you explained.But my situation is:
    there're almost one Thousand physic objects in my game,I do the physic work in C++ code. I have to process all the collisions and positions in Physic Tick.I'm not sure the overhead cost to pass a very large array while calling C++ function in every frame. void PhysicTick((Vecotr3 allpositions[2048]).
    What is the best practice ?
    Thank you!
     
  44. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    There are 2 ways out of it if you have an array of Vector3[] in managed land.

    First option: you could take a pinned GC handle to it, and pass GCHandle.AddrOfPinnedObject() tonative code. That would achieve a similar thing. However, pinning objects for prolonged period of time may induce a cost on some GC types (that is not the case of today's il2cpp garbage collector, but might be in the future).

    Second option, pass the pointer to the first element of the array to native code using unsafe block:

    C#:
    Code (csharp):
    1. [DllImport("__Internal")]
    2. public unsafe static extern void Move(Vector3* positions, int positionCount, float fDeltaTime);
    3.  
    4. private Transform[] objectTransforms;
    5. private Vector3[] objectPositions;
    6.  
    7. void Update()
    8. {
    9.     unsafe
    10.     {
    11.         fixed (Vector3* positionPtr = objectPositions)
    12.         {
    13.             Move(positionPtr, objectPositions.Length, Time.deltaTime);
    14.         }
    15.     }
    16.  
    17.     foreach (var position in objectPositions)
    18.         objectTransforms[i].position = position;
    19. }
    20.  
    C++
    Code (csharp):
    1. struct Vector3
    2. {
    3.    float x, y, z;
    4. };
    5.  
    6. EXPORT_API void Move(Vector3* positions, int positionCount, float fDeltaTime)
    7. {
    8.     for (int i = 0; i < positionCount; i++)
    9.     {
    10.         positions[i] = ...; // do your thing
    11.     }
    12. }
    Second option should theoretically be faster. Passing a pointer through P/Invoke is same as passing an integer: no marshaling will be done.
     
    Last edited: Nov 19, 2015
    landon912 likes this.
  45. tonydongyiqi1

    tonydongyiqi1

    Joined:
    Jun 30, 2015
    Posts:
    13
    Thank you so much~ i'm going to have a try right now~
     
  46. liortal

    liortal

    Joined:
    Oct 17, 2012
    Posts:
    3,562
    @Tautvydas Zilys how can you pass a Vector3 type (which is defined as a managed object) into native code and redefine that and everything just works?

    What assures you that the data layout is the same and that you will get passed an object with the correct data as in managed code ?
     
  47. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    Vector3 is not a managed object: it's managed struct with only 3 fields inside. Since it's a struct and doesn't have any managed class fields inside, the field layout is guaranteed to be deterministic.
     
    liortal likes this.
  48. tonydongyiqi1

    tonydongyiqi1

    Joined:
    Jun 30, 2015
    Posts:
    13
    @Tautvydas Zilys
    Thank you again for helping me out of this!
    Every thing works fine . performance is also pretty good.
     
  49. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,680
    Glad to help :).
     
  50. IntDev

    IntDev

    Joined:
    Jan 14, 2013
    Posts:
    152
    Right now, what platforms support IL2CPP? Thank you.
     
    Last edited: Nov 30, 2015