Create delegate at runtime from native method on i

2019-04-11 15:43发布

问题:

This is a MonoTouch-specific question.

I'm currently developing a wrapper for OpenGL which is quite different from wrappers like OpenTK. This wrapper is used to enable faster development with OpenGL.

Methods are not declared like this: void glGenTextures(Int32 n, UInt32[] textures);, they are declared like void glGenTextures(Int32 count, [Out]TextureHandle[] textures) where TextureHandle is a structure with the same size as a UInt32.

Question

On Windows i can use GetProcAddress, wglGetProcAddress and Marshal.GetDelegateForFunctionPointer to create a delegate from a method pointer, but how to do this on iOS with MonoTouch. Is there any way to this or is it not supported by monotouch yet?

回答1:

Starting with MonoTouch 5.4 this is possible. You need to create a delegate with the same signature as the managed method, and decorate it with the MonoNativeFunctionWrapper attribute:

[MonoNativeFunctionWrapper]
public delegate void glGenTexturesDelegate (int n, uint[] textures);

Now you can call the method:

var del = (glGenTexturesDelegate) Marshal.GetDelegateForFunctionPointer (pointer);
del (n, textures);

That said, I believe you're doing this a lot more complicated than you need to. Just use a P/Invoke:

[llImport("libGLESv2.dll")]
extern static void glGenTextures (int n, uint[] textures);

and then call it like this:

glGenTextures (n, textures);