Generics in C#

G

Guest

Hello,

I have been trying to write code with generics. But following syntax is bad,
in my opinion it shouldn't be.

--- CODE ---
public unsafe void Test2(void* data)
{
....
}

public unsafe void Test<T>(T value) where T : struct
{
Test2((void*)&value);
}
--- END CODE ---

Compiler says that "Cannot take the address of, get the size of, or declare
a pointer to a managed type ('T')"
but T is value type...
Is there any other solution's?
Sorry about my english...

Thanks.
 
G

Guest

I thick this is a solution

GCHandle dataHandle = GCHandle.Alloc(Data, GCHandleType.Pinned);
public void* pData = (void*) dataHandle.AddrOfPinnedObject();

as in the following class.

Unfortunatey you can't do this

public S* pData;
pData = ( S*) dataHandle.AddrOfPinnedObject();

Just the declare gives a compiling error
Does anyone know how to cast a pointer to a generic type?


this works

unsafe public class PinnedClass<S> where S : new()
{
public S Data;
public void* pData;
private GCHandle dataHandle;

public PinnedClass()
{
Data = new S();
dataHandle = GCHandle.Alloc(Data, GCHandleType.Pinned);
pData = (void*) dataHandle.AddrOfPinnedObject();
}

public void Pin()
{
UnPin();
dataHandle = GCHandle.Alloc(Data, GCHandleType.Pinned);
pData = (void*)dataHandle.AddrOfPinnedObject();
}

public void UnPin()
{
if (pData != null)
{
dataHandle.Free();
pData = null;
}
}


}

this is what I'd like but does not compile

unsafe public class PinnedClass<S> where S : new()
{
public S Data;
public S* pData;
private GCHandle dataHandle;

public PinnedClass()
{
Data = new S();
dataHandle = GCHandle.Alloc(Data, GCHandleType.Pinned);
pData = (S*) dataHandle.AddrOfPinnedObject();
}

public void Pin()
{
UnPin();
dataHandle = GCHandle.Alloc(Data, GCHandleType.Pinned);
pData = (S*)dataHandle.AddrOfPinnedObject();
}

public void UnPin()
{
if (pData != null)
{
dataHandle.Free();
pData = null;
}
}


}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top