开发者

pointer to a array of type generic? [duplicate]

This question already has answers here: C#: Using a generic to create a pointer array (2 answers) Closed 9 years ago. 开发者_C百科

I'd like to create a generic method that uses a pointer to an array of T where T could be a C# primitive, or a C# class. I was going along fine until I attempted the "T" part.

Is there a way around the error "can not declare a pointer to a non unmanaged type TIn"

I tried to use pinning via the "fixed" keyword to make this possible.

    public static object DoSomething<TIn, TOut>(object SObj, Action<TIn, TOut> takeAction)
    {
        double[]A = (double[]) SObj;
        TIn[]B = new TIn[5];
        unsafe
        {
            fixed (double* dbl = A) // <--- works okay
            {

            }
            fixed (TIn* Sptr = B)  // <--- fails
            {

            }
        }
    }

--

@dtb: just checked out blittable. "One-dimensional arrays of blittable types, such as an array of integers. However, a type that contains a variable array of blittable types is not itself blittable." Even if there was a biltable constraint, it seems like they've limited it to arrays of one dimension.


Essentially, no. You can't create a pointer to a managed type - only to certain primitive types and structs where all the fields are themselves structs or unmanaged types. Your generic parameter type will not have these properties, so it forbids construction of a pointer and gives you that error.

As per http://msdn.microsoft.com/en-us/library/y31yhkeb.aspx, pointers can be made to:

  • sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.

  • Any enum type.

  • Any pointer type.

  • Any user-defined struct type that contains fields of unmanaged types only.

Fortunately, as pointer arithmetic is impossible, there's not a whole lot of benefit to having a pointer to a managed type. Why do you want to build one?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜