mardi 23 mars 2021

Invoke MethodInfo with void* as a parameter

The problem

Theres an internal method i need to invoke via reflection. It looks like this...

internal void SetComponentDataRaw(Entity entity, int typeIndex, void* data, int size)

Obtaining the MethodInfo is no problem, but calling it is one. I need to pass a void pointer to it, but such a void pointer can NOT be cast to an object. When i box that pointer, i receive an error later on that tells me it can not unbox it properly.


var SetComponentDataRawInfo = typeof(...).GetMethod("SetComponentDataRaw", ...);
var entity = someEntityToPass;
var cmp = new StructToPassToTheMethodAsAPointer();

// My first attempt, not possible to cast
unsafe {
   var handle = GCHandle.Alloc(cmp, GCHandleType.Pinned);
   var adress = handle.AddrOfPinnedObject();
   var ptr = adress.ToPointer();
   var sizeOfComponent = UnsafeUtility.SizeOf(type);

   var parameters = new [] {entity, cmpType.TypeIndex, (object)ptr, sizeOfComponent}; // (object)ptr not possible
   SetComponentDataRawInfo.Invoke(em, parameters);
   handle.Free();
}


// Second attempt
unsafe {
   var handle = GCHandle.Alloc(cmp, GCHandleType.Pinned);
   var adress = handle.AddrOfPinnedObject();
   var ptr = adress.ToPointer();
   var sizeOfComponent = UnsafeUtility.SizeOf(type);

   var parameters = new [] {entity, cmpType.TypeIndex, Pointer.Box(ptr, typeof(void*)), sizeOfComponent};
   SetComponentDataRawInfo.Invoke(em, parameters);
   handle.Free();
}

The second attempt is able to invoke the method... but i receive the following exception : ArgumentException: Object of type 'System.Reflection.Pointer' cannot be converted to type 'System.Void*'.

The question

How do we invoke a MethodInfo with a pure void* as an parameter ? Glad for any help on this topic !





Aucun commentaire:

Enregistrer un commentaire