Code Reading #1: Slick callback registration in MonoDevelop

I’m starting a new category of blog posts called ”Code Reading” where I’ll talk about something interesting I saw during my week of coding, with some code snippets of course.

Just today, this caught my eye when I was trying to figure out how to hook into an event in the Vim addin that I was trying to package up. So there is a global preferences window where the user checks boxes to enable certain things, and one of them is vim input mode in the text editor. Basically, there’s a global PropertyService that exposes these selections, as well as fires an event when something is updated.

I found an example of how this event can be registered/unregistered in the SourceEditorOptions class. Registration happens in the constructor:

        DefaultSourceEditorOptions (MonoDevelop.Ide.Gui.Content.TextStylePolicy currentPolicy)
        {   
            LoadAllPrefs (); 
            UpdateStylePolicy (currentPolicy);
            PropertyService.PropertyChanged += UpdatePreferences;
            ... 

And unregistration happens in the destructor:

        public override void Dispose()
        {   
            PropertyService.PropertyChanged -= UpdatePreferences;
            FontService.RemoveCallback (UpdateFont);
        } 

So PropertyChanged shows up in PropertyService on line 270:

public static event EventHandler<PropertyChangedEventArgs> PropertyChanged;

The interesting thing to me is the event keyword, which means there’s language-level support for event handling.

It’s really slick syntax to just add or subtract your event handler to the event as the highlighted lines above show. Let’s just peek at what that event handler looks like:

        void UpdatePreferences (object sender, PropertyChangedEventArgs args)
        {   
            try {
                switch (args.Key) {
                    case "TabIsReindent":
                    this.TabIsReindent = (bool)args.NewValue;
                    break;
                    case "EnableSemanticHighlighting":
                    this.EnableSemanticHighlighting = (bool)args.NewValue;
                    break;
                    ... 

So it’s interesting that you can just pass the member function around. There’s magic that happens inferring the type of that thing, but the point is that it is a first-class object. Here’s another more explicit example elsewhere:

            properties.PropertyChanged += delegate(object sender, PropertyChangedEventArgs args) {
                if (PropertyChanged != null)
                    PropertyChanged (sender, args);
            }; 

I guess it’s a lambda function, but not quite, because they call it a delegate. But it has the signature and the body, all the same.

Well, I was really impressed when I tried to plug my own function in and got a compiler error indicating what the signature should have been. I wonder where it is specified and also where the event is generated. It’s a mystery to me, but I know that it’s a lot more heavyweight to achieve in C++.

Advertisements

Getting started with CppSharp

CppSharp is one cool project that generates C# bindings for C++ libraries. It’s under active development now and I finally got around to getting a sample up and running on OSX. Here’s a running example from following the Getting Started guide on the github page.

First, you’ll need to set yourself up with Mono. I set mine up through a Homebrew keg, and it set me up with a 32-bit runtime. So that means we need to make sure that C++ library we interface with is compiled for 32-bits.

Here’s a sample library. Make it and extract the archive into the working directory. You’ll see the following structure get unpacked:

libsample
libsample/include
libsample/lib

Next, you’ll need to clone and build CppSharp. The Getting Started page is the quickest way to build it. In short, you

  1. Clone the particular revisions of LLVM and Clang into the tools subdirectory.
  2. Configure and build LLVM with CMake, enabling C++11 and libc++ standard library support by adding cache entries LLVM_ENABLE_CXX11 and LLVM_ENABLE_LIBCXX.
  3. Configure and build CppSharp. They use premake as their build system, which is a lot simpler to deal with.

The result of building CppSharp is a set of .dlls. The easiest thing is to copy all the resulting .dll files to the working directory of where the executable for your binding generating code will go. Otherwise, you will need to add the directory containing these libraries to MONO_PATH.

To generate your bindings for libsample, you implement ILibrary. Here’s a barebones example that compiles and runs. It assumes you’ve got the following in your working directory:

lib/Release_x32/
libsample/{include,lib}

The binding generator is Sample.exe. parses the sample library and spits out bindings in the out/ directory.

Then you can proceed to use your C++ assets from C# — TestSample.exe compiled in the barebones example above will show you how. You just have to make sure the .dylib is in the working directory or visible through LD_LIBRARY_PATH.

Now that I’ve got this up and running, I’m looking into experimenting with QtSharp. Now that I kind of see what’s going on, it looks like the developer has committed bindings for Qt5. I guess the path of least friction is to do the same rather than mess around with Qt4. I just built 32-bit Qt5 overnight last night and will be testing it shortly.

Nice projects in C#

So I’ve been reading up on C# recently and toying around with writing example code, and at the same time, I’ve been looking at what libraries are out there to work with. For example, I’d naturally wonder how I could rebuild my project in C# that I’ve been working on as a grad student.

There seems to be very current effort to produce C# bindings for Qt: https://github.com/ddobrev/QtSharp. There’s not much in the way of documentation at all, but I assume it is a fork from an old project called Qyoto, which as I understand provided Qt bindings for Mono/KDE apps. So I don’t know to what extent this current project supports Qt4 versus Qt5, but I think it’s something I want to get to know because it really is all about interfacing with an existing C++ library and making it operate within a managed C# environment.

OpenTK is another nice one under active development: sourceforge.net/projects/opentk/. I have always felt incomplete working in the area of graphics without actually learning graphics from the ground up and getting hands on with OpenGL, and this looks like the perfect excuse to do it. Just looking at the quick 15 minute introduction, they show off some fancy C# way of what looks like specifying callbacks. It also exposes OpenAL API for audio, which makes me think of SDL, which interestingly also has C# bindings.

SimpleITK (http://sourceforge.net/projects/simpleitk/) is another cool API that is actively maintained. Unfortunately you have to deal with the ITK-quality documentation, which at best leaves something to be desired. But judging from the autocompletion, there’s a significant part of the image-processing API exposed. I think I definitely want to toy around with manipulating MRI images, which I ostensibly should be pretty familiar with but am actually not ever since I’ve been enlisted on this geometry processing project that is my thesis topic.

Hope to post more about these as I play and learn. P.S. Yay, first C# tagged article. Sadly, using the string “C#” as the tag ends up tagging the article as C++, so it’ll have to be csharp.