I use C interfaces that have a callback function where the software works with a pointer.
On the C # side, I have the following code to copy a pointer to and from a managed array, for example. for float *.
class FloatPointer
{
readonly unsafe float* _pointer;
public uint Size { get; set; }
public float[] Array { get; set; }
public unsafe void CopyToPointer ()
{
int length = (int)Math.Min (Size, Array.Length);
Marshal.Copy (Array, 0, (IntPtr)_pointer, length);
for (int i = length; i < Size; i++) {
_pointer [i] = 0;
}
}
unsafe float[] CopyFromPointer ()
{
float[] result = new float[Size];
Marshal.Copy ((IntPtr)_pointer, result, 0, (int)Size);
return result;
}
public unsafe FloatPointer (float* pointer, uint size)
{
_pointer = pointer;
Size = size;
Array = CopyFromPointer ();
}
}
How should I do the same for unsigned char*, uint*etc., I was thinking about using a common class for it class Pointer<T>: where T: ValueType.
Unfortunately, this restriction is not possible.
If I changed this to an unlimited general class, then Marshal.Copyit tells me that he does not know about T[].
Is there any way to create this generic class?
source
share