How int* is bool in C#?
I am trying to use pointers in C# like in C.
public static void Main(string[] args)
{
unsafe
{
int i = 5;
int* j = &i;
Console.WriteLine(j); //cannot convert from 'int*' to 'bool'
}
}
开发者_如何学Go
I have two queries regarding this code:
- How to compile with /unsafe ?
- Why
Console.Writeline(j)
is trying to convertj to bool
?
Point 2) takes 2 steps:
Console.WriteLine()
does not have an overload forint*
- Apparently it then tries it's first overload,
WriteLine(bool value)
and cannot find a conversion
I would call this a weak error report.
To print the address, cast it to an ulong
first.
- If using csc, add /unsafe; or in a vs project, go to project properties and there is a checkbox
- Simply it can't find a better match; I'd have to check the spec for the exact order rules, but just treat it as the compiler saying "no suitable match, I'm guessing at this but this doesn't work either"
Writing the value of the pointer is pointless, it is just a random address. You initialize the pointer with the address of a variable on the stack, such an address doesn't repeat well. You want to dereference the pointer with the * operator. Like this:
Console.WriteLine(*j);
Which writes the pointed-to value, 5 in your case.
精彩评论