Oscar Papel's Web Log

Thursday, November 11, 2004

Damocles is Sharp!

Damocles can also be used from any managed language. Known as DamoclesSharp, it is a library that provides managed wrappers or equivalents to the C "objects" of Damocles. A typical class looks like the following:


public class Image : IDisposable {

private IntPtr nativePtr=NULL;

public Image() { ... }
public Image(IntPtr NativePtr) { ... }
~Image() {....}

#region IDisposable implementation
...
#endregion

#region Interop calls
[DllImport(Damocles.DllName)] private static extern IntPtr AllocateImage(...)
[DllImport(Damocles.DllName)] private static extern void AddImageReference(...)
[DllImport(Damocles.DllName)] private static extern void FreeImage(...)
... other Interop functions here ...
#endregion

}



The class is implemented with the unmanaged resources design pattern. That is, it creates, modifies, and frees an unmanaged resource (in this case, our C "object"). It implements IDisposable to signal that it contains unmanaged resources and it implements a finalizer that works with the IDisposable implementation to ensure that the C "object" will be freed when the managed object is. Again, the object can create the underlying C "object" or can be created to wrap an existing one.

Just like the ObjC implementation, the C# implementation works with the C memory management to ensure no memory leaks.

Also like the ObjC implementation, there are some optimizations in place. Since the IntPtr is just a managed wrapper around a pinned address to memory, there is no need to cross the interop boundary to read/write the contents of the underlying object. Care has been taken to compensate for the size of the pointer during this. As a result, reading and writing the object properties can be done without incurring an interop penalty. Again, just like the ObjC optimizations, any code using the class is completely unchanged and continues to work as before.

This code wraps Damocles.dll on the PC and libDamocles.dylib on the Mac. A simple config file makes this interop layer code portable.

0 Comments:

Post a Comment

<< Home