Skip to content

Il2CppSystem.String static constructor does not initialize Il2CppClassPointerStore<Il2CppSystem.String>.NativeClassPtr #224

@Dwedit

Description

@Dwedit

You have a Il2CppSystem.Object. You get an exception any time you use TryCast to turn the object into a Il2CppSystem.String or any generic type that contains Il2CppSystem.String.
It turns out you should just never use Il2CppSystem.String at all. Using just string is fine.

I got burned by this issue two times.

One time, I was trying to cast an object (it's a List<string>) out of the object type. I was trying to use TryCast to change the Il2CppSystem.Object into a Il2CppSystem.Collections.Generic.List<Il2CppSystem.String>. But I should have picked the type Il2CppSystem.Collections.Generic.List<string> instead, I just didn't realize it.

The other time was when I was trying to see if an object was a string or not. I have a Il2CppSystem.Object, and want to know if it's a string. If you try to use TryCast to see if it can turn into a Il2CppSystem.String, you get an exception. There is no option to use TryCast with the string type, since it doesn't inherit from Il2CppObjectBase.

Anyway, I was investigating why this was happening and what was going on.

It appears that Il2CppSystem.String has a static constructor that does not initialize Il2CppClassPointerStore<Il2CppSystem.String>.NativeClassPtr. Instead, it writes to Il2CppClassPointerStore<System.String>.NativeClassPtr (the actual string type).
And the static constructor for a generic type such as Il2CppSystem.Collections.Generic.List<Il2CppSystem.String> will try to use the field Il2CppClassPointerStore<Il2CppSystem.String>.NativeClassPtr, but that field is always null, so you get an exception.

To stop the exceptions, the static constructor for Il2CppSystem.String could write to both Il2CppClassPointerStore<Il2CppSystem.String>.NativeClassPtr and Il2CppClassPointerStore<System.String>.NativeClassPtr. But I don't know if that's what's wanted or not.

Maybe put [Obsolete] on the class Il2CppSystem.String to discourage people from trying to use it?

Casting from Il2CppSystem.Object to String is still a bit hairy since there is no TryCastString method. You need to find out if the Type pointer is the type pointer for a string, or call TypeFromPointer and look at the type's name, then use Il2CppStringToManaged.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions