For example, as an overloaded []
setter-getter,
public T this[int i]
{
get
{
unsafe
{
T* p = (T*)hArr.ToPointer(); // hArr is a C++ object pointer(IntPtr)
return *(p + i);
}
}
set
{
unsafe
{
T* p = (T*)hArr.ToPointer();
*(p + i) = value;
}
}
}
and compiler complains(underlines) about it "cannot take address of ..." to a managed type T
.
I know T
will be only float,double,int or byte in runtime but I don't know how to tell this to compiler so it trusts me.
Why can't I use it, all are pointers anyway, I can overflow any type of array if I'm not careful.
How can I achieve this(with a similar way or another) without being much slower than:
public float this[int i]
{
get
{
unsafe
{
float* p = (float*)hArr.ToPointer();
return *(p + i);
}
}
set {
unsafe
{
float* p = (float*)hArr.ToPointer();
*(p + i) = value;
}
}
}
I don't just care about performance here, but also code simplicity too. (one code for all T types) Interfaces can't help here I suppose.