Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IL: ldfld vs ldflda

Tags:

c#

.net

il

I'm writing a small IL-weaving application using Mono.Cecil, that requires me to manipulate the target assembly on an IL level.

My question is quite simple, but I still find the matter very confusing. What is the practical difference between the ldfld and ldflda instructions?

I have consulted with msdn, and it appears that while ldfld fetches the value of the field, ldflda gets the address of the field. Okay... but what does this mean? I first thought that the former is used for value types (and string), and the latter for reference types, but I have compiled a C# snippet and checked it in Reflector, and it proved me wrong.

I haven't been able to find any distinct pattern in when the C# compiler emits ldflda instead of ldfld, and my searches didn't reveal any articles that would explain this. So when to use ldflda instead of ldfld?

Any help would be very much appreciated.

like image 799
ShdNx Avatar asked Apr 29 '11 18:04

ShdNx


2 Answers

I guess it is used for structures:

struct Counter
{
   public int i;
}

struct Something
{
   public Counter c;
}

Something s;
s.c.i++;

I am pretty sure c here is loaded by address otherwise it would create a copy of Counter. That's why you can't do this with propery.

like image 168
Andrey Avatar answered Oct 14 '22 04:10

Andrey


If you pass a field to a subroutine as a ref parameter, you should see the compiler emit a ldflda for it in order to obtain the reference to pass in.

like image 42
500 - Internal Server Error Avatar answered Oct 14 '22 04:10

500 - Internal Server Error