Can I add a field to compiled class?
I'm making a mod for a game and I need to give a class some extra information. I don't have access to how its constructed so I can't do type building. I can't replace dll's because this is a plugin. Is what I need to do possible with those restrictions?
19 Replies
do you actually need to modify the class or do you just need to associate information with it?
I need to give it a variable so i can use it inside the class. I have a thing for like hooking into a method to add code to it, and I need to do that, but I need to use a variable specific to the class
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.conditionalweaktable-2?view=net-8.0 is a way to associate data with an object
ConditionalWeakTable Class (System.Runtime.CompilerServices)
Enables compilers to dynamically attach object fields to managed objects.
it's like a dictionary that automatically cleans up entries when the key is GCed
I KNEW TGHERE WAS A BETTER WAY TO DO THAT
thank you
so instead of modifying the class directly you can use one of these and for each class add an entry with the class as the key and your custom data as the value
i'd personally write some extension methods to make it more convenient to use
like
int GetMyInt(this ClassICantModify obj)
Where would I put that
sec, i'll wite a more thorough example
then you'd use this inside the class you're patching like
ohhh okay
tysm
is CWT thread safe?
ah yep
actually @LudoCrypt @Jimmacle, probably should use GetOrCreate https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.conditionalweaktable-2.getorcreatevalue?view=net-8.0
ConditionalWeakTable.GetOrCreateValue(TKey) Method (System.Runtime....
Atomically searches for a specified key in the table and returns the corresponding value. If the key does not exist in the table, the method invokes the parameterless constructor of the class that represents the table's value to create a value that is bound to the specified key.
rather than a separate check then add
ah, yeah i just did it from limited memory of using it years ago
ohh
that might explain why the screen kept going black
dunno about that, but it's more correct either way
it only really affects the first time it's accessed
well it only happens when i call the get data method so iunno
there's probably another issue
"screen goes black" isn't much info to go on
yea which is why i didnt say anything
if you are using Unity, chances are that you can use BepInEx lib