I am resorting to a horrible hack in order to fill a locked-down data type in the XNA framework: there’s an internal method in a structure that I wish to call without feeding the garbage collector.
If I keep said structure boxed in an object variable and use MethodInfo.Invoke(), that call would itself feed the garbage collector by boxing the parameters:
private object boxedTouchCollection;
void test() {
MethodInfo addTouchLocationMethod = typeof(TouchCollection).GetMethod(
"AddTouchLocation", BindingFlags.Instance | BindingFlags.NonPublic
);
addTouchLocationMethod.Invoke(
this.boxedState, new object[] { /* parameters being boxed */ }
);
}
I’m not sure whether Delegate.CreateDelegate() can be used here – can I just turn the first parameter into an object and it will work on the boxed structure? Or can I store my structure unboxed and declare the first parameter as ref TouchCollection?
delegate void AddTouchLocationDelegate(
ref TouchCollection collection,
int id,
// ...more parameters...
);
private TouchCollection touchCollection;
void test() {
Delegate.CreateDelegate(
typeof(AddTouchLocationDelegate),
typeof(ref TouchCollection), // doesn't compile
addTouchLocationMethod
);
}
Is there a way I can make Delegate.CreateDelegate() work?
Or will I have to resort to dynamic IL generation?
Here’s one way.
It relies on this overload of
Delegate.CreateDelegate, which creates open instance-method delegates. The only tricky bit is that so you’ll have to create the appropriate delegate-type to be able to pass the struct by reference.I don’t think there should be any boxing with this technique – either with the arguments to the method, or with the struct itself.
Example: (Apologies for simplifying the example-types)