Cryptic compiler error with sizeof/unsafe code

The following code compiles ok for .NET 4.5 (with the /unsafe compiler flag), but compiling for netmf 4.3, I’m getting the following two errors:

[ul]“Cannot parse method signature ‘F’”[/ul]
[ul]CLR_E_FAIL[/ul]

It looks like the error depends on the use of sizeof(), although the same compiles ok if used on int instead of a struct type…

Anybody know what’s wrong?

The code:


public struct A
{
    public int a;
}

unsafe public static int F()
{
    return sizeof(A);
}

Does it make any difference if you create an instance of A return size of the instance?

I believe the unsafe keyword is usually used with pointers which are not supported by MF.

as far as I understand the spec, sizeof() only works on types, not instances in C#.

And the other option of getting sizes of structs in .NET, Marshal.SizeOf(), seems unavailable in MF - or am I missing anything?

Although that seems to be unrelated here (since my example doesn’t use any pointers) this is interesting. I was not aware that pointers were not supported in MF. So that inspires me to more experiments now, of course… :slight_smile:


unsafe public static void F()
{
    int a = 1;
    int* aptr = &a;
    int b = *aptr;
    Debug.Print("a: " + a + " b: " + b + "\r\n");
}

compiles without complaint, but throws an exception on the Debug.Print() statement (although the interesting pointer stuff happens before).

But if I only use Print() outside the unsafe function, everything seems to work alright:


public static void Main()
{
    byte b = F();
    Debug.Print("b: " + b + "\r\n");
}

unsafe public static byte F()
{
    int a = 1;
    byte* aptr = (byte*)&a;
    return *aptr;
}

will print
b: 1

Modifying aptr inside F() does throw an exception, though. So that “pointers support” may not be of any use if you can’t do pointer arithmetics…

I would love to read some background of unsafe/pointer support in MF, if anybody can provide any links.

Unsafe instructions are not supported in MF, so there is nothing to read about unsafe support.

ok… it just seems that the compiler does not know about that limitation, and fails to provide any understandable error message.

The above mentioned cases where unsafe code compiles and works ok in MF are probably the ones where the unsafe instructions were optimized away by the compiler?
(sizeof() of primitive types and dereferencing of unchanged pointers)

Compiler does not check this at compile time. You can write unsafe instructions, for example pin memory with fixed keyword and it will compile ok, but exception will be thrown during execution.

Although it does not explain the [em]compiler errors[/em] I got, I guess this information renders my question quite academic. I’m marking it as answered. Thanks