CosmosOS / Cosmos

Cosmos is an operating system "construction kit". Build your own OS using managed languages such as C#, VB.NET, and more!
https://www.goCosmos.org
BSD 3-Clause "New" or "Revised" License
2.85k stars 536 forks source link

Plugged `System.Activator.CreateInstance` methods for types with parameterless constructors. #2997

Closed Guillermo-Santos closed 1 month ago

Guillermo-Santos commented 1 month ago

This PR add the plugs for System.Activator.CreateInstance<T>() and System.Activator.CreateInstance(Type T, bool, bool) two methods that are used to create generic types.

With System.Activator.CreateInstance<T>() the following start to work on cosmos:

// A generic method to get an instance of type T
public static T Get<T>() where T : class, new()
{
    return new T();
}

Limitations

  1. Constructors may not be on the compilation result:At the moment Constructors, as any other method, are not included on the compilation result if never called, this could cause stack corruption or null reference exceptions when calling one of these methods or when using its result.

To avoid this, you would need to add a dummy variable somewhere (BeforeRun recommended) to make IL2CPU include the ctor on the compilation.

var dummy = new MyClass();
var myVar = Activator.CreateInstance<MyClass>();//This will work as ctor is included on the compilation.
  1. ref struct should not be supported: If the type you are trying to instantiate is a ref struct these methods should throw a NotSupportedException (as far as I know, is because ref struct should never be boxed), but since, at the moment, we cannot check if a type is a ref struct (System.Type.IsByRefLike field not plugged) we just process the ref struct and return it as a normal struct or class.
zarlo commented 1 month ago

ref struct should not be supported: If the type you are trying to instantiate is a ref struct these methods should throw a NotSupportedException (as far as I know, is because ref struct should never be boxed), but since, at the moment, we cannot check if a type is a ref struct (System.Type.IsByRefLike field not plugged) we just process the ref struct and return it as a normal struct or class.

@Guillermo-Santos if it has not already been done could you make a issue for this so we can track it

Guillermo-Santos commented 1 month ago

ref struct should not be supported: If the type you are trying to instantiate is a ref struct these methods should throw a NotSupportedException (as far as I know, is because ref struct should never be boxed), but since, at the moment, we cannot check if a type is a ref struct (System.Type.IsByRefLike field not plugged) we just process the ref struct and return it as a normal struct or class.

@Guillermo-Santos if it has not already been done could you make a issue for this so we can track it

Will do