C# 2.0 Generics: how to get address of data?

  • Thread starter Thread starter DaZoner
  • Start date Start date
D

DaZoner

I'm using the 2.0 SDK and learning to use Generics. I'm trying to
obtain a pointer to a buffer (one of the members of a class) so that I
can pass it on to some unmanaged code. The code I have generates a
couple of compiler errors and I'm wondering how to work around them.
I've put the error messages below as comments just after the offending
lines. Can someone tell me how to accomplish what I'm after?


using System;

class Flub<T>
{
T[] data;

public Flub()
{
data = new T[4];
}

void ReadPixels(IntPtr buffer)
{
// call DLL
}

unsafe void Attempt1()
{
unsafe {
fixed(void* buffer = data) {
// ERROR ABOVE: cannot take the address of, get the size of, or
declare a pointer to a managed type ('T')
ReadPixels((IntPtr)buffer);
}
}
}

unsafe void Attempt2()
{
string typename = typeof(T).FullName;

if (typename == "System.Int32")
{
int[] ints = new int[data.Length];
unsafe {
fixed (int* ip = ints)
{
ReadPixels((IntPtr)ip);
for (int i = 0; i < ints.Length; i++)
data = (T) ints;
// ERROR ABOVE: cannot convert type 'int' to 'T'
}
}
}
else
throw new SystemException();
}

}

The two error messages are pretty self explanatory. I'm surprised by
the second as I thought it would try to cast at runtime and throw an
exception if it couldn't.

The first message is a little unexpected as well. I know I can do
this:

public unsafe static void changeVal(int[] a)
{
fixed (int *b = a)
{
*b = 5;
*(b + 1) = 7;
}
}
.... assuming 'a' has already allocated space for two ints. But isn't
'a' a managed type too? Why can I get its address?
 
Can someone tell me how to accomplish what I'm after?

Unfortunately you can't.

... assuming 'a' has already allocated space for two ints. But isn't
'a' a managed type too? Why can I get its address?

Because it's not known at compile time that T will be a "managed
type".



Mattias
 
Surely there must be some way to get data from unmanaged code into a
generic data structure through a pointer. Specifically I picture
having a Raster generic that can have different underlying datatypes
(byte, ushort, uint). Can anyone tell me how I can do it? Or is it
really not possible?
 
Back
Top