Saturday, 15 June 2013

c# - How to use fixed with a variable of type Array or T[]? -



c# - How to use fixed with a variable of type Array or T[]? -

i'm working on iequalitycomparer supposed compare arrays of primitive types fast. plan obtain pointers arrays , memcmp them. this:

public unsafe override bool equals(t[] x, t[] y) { if (referenceequals(x, y)) homecoming true; if (x == null || y == null) homecoming false; if (x.length != y.length) homecoming false; var xarray = (array)x; var yarray = (array)y; fixed (void* xptr = xarray) //compiler error 1 fixed (t* yptr = y) //compiler error 2 { homecoming memcmp(xptr, yptr, x.length * this.elementsize); } }

the fixed statement not allow me pin either array or t[].

there error messages are:

1. cannot implicitly convert type 'system.array' 'void*' 2. cannot take address of, size of, or declare pointer managed type ('t')

now, don't care how create work (i'm not committed exact approach). how can memcmp 2 t[] know t primitive/blittable type?

i want avoid switching on type , creating specialized (and duplicated) code version each interesting type. kind of reflection solution not workable due performance constraints (and yes need performance here - no premature optimization warnings apply customary on stack overflow).

where know t primitive/blittable type

you know it, compiler doesn't know that. clr demands everything in pinned object can no longer moved garbage collector. array, includes array elements. kind of t qualifies simple value type, 1 blittable. generics not give way constrain t blittable type.

you'd declare arguments of memcmp() byte[]. pinvoke marshaller right thing , pin byte[] arrays before calling memcmp(). not work either since cannot convert t[] byte[] either. you'll have pin gchandle. declare memcmp() arguments intptr instead of byte[] accordingly.

the subset of types can work in practice little plenty consider writing method overloads instead of generic method. enables pinvoke marshaller take care of pinning, overload memcmp() function declarations accordingly.

c# fixed unsafe

No comments:

Post a Comment