|Project:||The Open Toolkit library|
Object overloads wrap native functions that take
void* parameters. OpenTK pins the parameter specified by the user and passes the address down to the unmanaged library.
OpenGL and OpenAL interact with value types or arrays of value types (i.e.
Vector3 and similar types, as well as combinations and arrays of those). However,
object overloads completely suppress type-checking and allow the user to pass any managed type to unmanaged code. This is unintuitive and potentially dangerous (crash-prone).
It is not possible to specify beforehand every possible structure the user may want to use. As a compromise, it is possible to use generic parameters to allow only
ref T parameters,
where T : struct. While this is not a 100% fail-safe solution (the
struct constraint allows references to reference types), it should significantly reduce the dangers introduce by the type-less
object overloads, with no loss of functionality. As an added advantage, these overloads will be symmetric to existing typed array overloads (i.e.
ref T to
Because the pinvoke layer cannot deal with generic parameters, we need to pin and pass a pointer instead. With this implementation, a hack may be employed to avoid using the heavy-weight
GCHandle class: a C# union can cast
T to a
byte, allowing us to obtain a direct pointer to the underlying data.
This trick works on both .Net and Mono, seemingly without side-effects. A proof of concept is attached (the solution is intended for MonoDevelop 2 beta 1 or higher. It will probably require some modifications to work with Visual Studio or SharpDevelop). Note that you might need to copy manually the native library to the same directory as the managed exe.
|ArrayInteropHack v1.zip||9.12 KB|