Question

I'm working on a program that pre-compiles bytecode from .NET assemblies. This program is itself a .NET program - so far I've been able to use reflection to extract all the needed information including the bytecode itself. However, I've run into a problem implementing the translation for ldfld.

ldfld and similar instructions have a metadata token within their encoding which references a FieldRef or FieldDef. I understand these are elements in metadata tables embedded in the assembly's PE file. In the worst-case I do have enough information from ECMA-335 to open the PE file and look all this up myself, but that's a lot of work and is not consistent with other information which I do get through Reflection, so I would prefer to do this lookup via Reflection.

However, I can't seem to find any methods on System.Reflection.Assembly that look up a metadata token. (I may have just missed it.) I can't do the lookup on anything more specific than an assembly because I only know the referencing assembly until I see the metadata (catch-22.) In fact, as noted in the comments, I don't even know what assembly the field is defined in, until examining the metadata.

Is there any way to look up such metadata tokens via Reflection?

Was it helpful?

Solution

You didn't find anything on Assembly, because FieldDef and FieldRef don't belong to an assembly, they belong to a module (most assemblies have just a single module, but they can have more). And Module has exactly the method you want: ResolveField(). You would use it something like this:

Module module = …;
int fieldToken = …;
FieldInfo field = module.ResolveField(fieldToken);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top