Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use GcHandle.Alloc to pin an array of enums

Tags:

c#

pinvoke

I want to do the following:

public enum Blah
{
    A,B
}

[Test,Explicit]
public void TestEnumGcHandle()
{
    var ea = new Blah[10];
    GCHandle.Alloc(ea, GCHandleType.Pinned);
}

but I get:

System.ArgumentException : Object contains non-primitive or non-blittable data.

Are .net Enums blittable types? (Marshalling) claims that Enums are blittable, but I can't pin an array of them. Could this be a bug in GcHandle.Alloc? I'm using .NET 3.5.

like image 891
pmarks Avatar asked Oct 09 '22 20:10

pmarks


1 Answers

It is a little heavy-handed in my book but enums are not primitive (typeof(Blah).IsPrimitive is false) and not blittable. It is missing from the list of blittable types. The linked SO question is wrong about that. Problem is that there's no way to find out what the size of the underlying integral type for the native enum might be. Heavy handed, I think, because there certainly is a way to specify it in the managed enum type. Well, can't do it.

like image 64
Hans Passant Avatar answered Oct 27 '22 20:10

Hans Passant