Phalanger's PHP on Mono/.NET Updates

by Miguel de Icaza

The Phalanger developers have published an updated set of benchmarks of their PHP compiler running on top of .NET vs PHP and Cached PHP, and the results are impressive:

There are two cases on the language shootout where they are slower than PHP (out of eighteen cases) and they are also slower on eight of thirtyone microbenchmarks.

But in general with real applications like WordPress and MediaWiki, the performance gains are impressive.

Posted on 05 Mar 2012


Working With SGen

by Miguel de Icaza

As SGen becomes the preferred garbage collector for Mono, I put together the Working With SGen document. This document is intended to explain the options that as a developer you can tune in SGen as well as some practices that you can adopt in your application to improve your application performance.

This document is a complement to the low-level implementation details that we had previously posted.

Posted on 05 Mar 2012


Gtk+ and MacOS X

by Miguel de Icaza

We have released a new build of Mono 2.10.9 (Beta) with the latest version of Gtk+2 containing dozens of bug fixes done by the Lanedo team to improve the quality of Mono/Gtk+ apps on OSX.

This is still a beta release, please take it out for a spin, we are almost ready to graduate this as our stable Mono package.

Posted on 05 Mar 2012


C# for Gaming: Slides

by Miguel de Icaza

You can now get the Slides for my Mono for Game Development talk.

Or you can go straight to the resources for the talk.

Posted on 11 Feb 2012


C# for Gaming: AltDevConf This Weekend

by Miguel de Icaza

It is a great honor to participate this weekend on the online AltDevConf conference. This is an online two-day event

Our goal is twofold: To provide free access to a comprehensive selection of game development topics taught by leading industry experts, and to create a space where bright and innovative voices can also be heard. We are able to do this, because as an online conference we are not subject to the same logistic and economic constrains imposed by the traditional conference model.

I will be participating in the talk on Cross Platform Game Development using C# with Matthieu Laban and Philippe Rollin.

You can register here for our session on Saturday at 3pm Eastern Standard Time, noon Pacific Time, and 9pm Paris Time.

If you are located in the Paris time zone, that means that you get to enjoy the talk sipping a tasty hot chocolate with some tasty baguettes.

Posted on 09 Feb 2012


Mono in 2011

by Miguel de Icaza

This was a very interesting year for Mono, and I wanted to capture some of the major milestones and news from the project as well as sharing a bit of what is coming up for Mono in 2012.

I used to be able to list all of the major applications and great projects built with Mono. The user base has grown so large that I am no longer able to do this. 2011 was a year that showed an explosion of applications built with Mono.

In this post I list a few of the high profile projects, but it is by no means an extensive list. There are too many great products and amazing technologies being built with Mono, but a comprehensive list would take too long to assemble.

Xamarin

The largest event for Mono this year was that the team working on Mono technologies at Novell was laid off after Novell was acquired.

We got back on our feet, and two weeks after the layoffs had taken place, the original Mono team incorporated as Xamarin.

Xamarin's goal is to deliver great productivity and great tools for mobile developers. Our main products are Mono on iOS and Mono on Android.

These products are built on top of the open source Mono project and the MonoDevelop project. We continue to contribute extensively to these two open source projects.

Launching Xamarin was a huge effort for all of us.

Xamarin would not have been possible without our great customers and friends in the industry. Many people cared deeply about the technology and helped us get up and running.

In July, we announced an agreement with Attachmate that ensured a bright future for our young company.

A couple of days later, we were ready to sell the mobile products that had been previously developed at Novell, and we started to provide all existing Novell customers with ongoing support for their Mono-based products.

Half a year later, we grew the company and continued to do what we like the most: writing amazing software.

Meanwhile, our users have created amazing mobile applications. You can see some of those in our App Catalog.

C# Everywhere

On the Mobile Space: This year Sony jumped to C# in a big way with the introduction of PS Suite (see the section below) and Nokia adopted Windows Phone 7 as their new operating system.

And we got you covered on Android and iOS for all of your C# needs.

On the Browser: we worked with Google to bring you Mono to Native Client. In fact, every demo shown at the Google Native Client event on December 8th was powered by Mono.

On the Desktop: this year we added MacOS X as a first-class citizen in the world of supported Mono platforms. We did this by introducing MonoMac 1.0 and supporting Apple's MacStore with it.

Games: continue to take advantage of C# blend of performance and high-level features. Read more on my GDC 2011 post.

It is a wild new world for C# and .NET developers that were used to build their UI using ASP.NET or Winforms only. It has been fascinating to see developers evolve their thinking from a Microsoft-only view of the world to a world where they design libraries and applications that split the presentation layer from the business logic.

Developers that make this transition will be able to get great native experiences on each device and form factor.

Sony PSSuite - Powered by Mono

At GDC, Sony announced that PS Suite was built on top of Mono. PS Suite is a new development stack for cross-platform games and cross-platform applications to run on Android devices and Sony Vita.

The PS Suite presentation is available in this video.

In particular, watch the game in Video 2 to get a feeling for the speed of a 3D game purely written in managed code (no native code):

Some of the juicy details from the GDC announcement:

  • PS Suite will have an open appstore model, different than the traditional game publishing business.
  • Open SDK, available for everyone at launch time.
  • PS Suite supports both game development with Sony's 3D libraries as well as regular app development.
  • Cross-platform, cross-device, using the ECMA Common Intermediate Language.
  • Code in C#, run using Mono.
  • GUI Designer called "UI Composer" for non-game applications.
  • The IDE is based on MonoDevelop.
  • Windows-simulator is included to try things out quickly.

MonoDevelop on PSSuite:

PS Suite comes with a GUI Toolkit and this is what the UI composer looks like:

Google Native Client

Google Engineers ported Mono to run on the sandboxed environment of Native Client. Last year they had added support for Mono code generator to output code for Native Client using Mono's static compiler.

This year Google extended Native Client to support Just in Time Compilation, in particular, Mono's brand of JIT compilation. This was used by all three demos shown at the Google Native Client event a couple of days ago:

Unity Powered Builder

This is another game built with Unity's Native Client code generator:

To get the latest version of Mono with support for Native Client, download and build Mono from Google's branch on github.

Mono 2.10

This was the year of Mono 2.10. We went from a beta release for Mono 2.10 in January to making it our new stable release for Mono.

While the world is on Mono 2.10, we have started our work to get Mono 2.12 out in beta form in January.

Mono on Android

This year we launched Mono for Android, a product that consists of port of Mono to the Android OS, C# bindings to the native Java APIs and IDE support for both MonoDevelop and Visual Studio.

The first release came out in April, it was rough around the edges, but thanks to the amazing community of users that worked with us during the year, we solved the performance problems, the slow debugging, vastly improved the edit/debug/deploy cycle and managed to catch up to Google's latest APIs with the introduction of Mono for Android 4.0.

Mono on iOS

Just like Android, we have been on a roll with MonoTouch.

In short, this year:

  • We kept up with Apple's newly introduced APIs (UIKit, iCloud, Airplay, Bluetooth, Newstand, CoreImage).
  • Integrated XCode 4's UI designer with MonoDevelop< and added support for storyboards.
  • Added the option of using LLVM for our builds, bringing thumb support and ARMv7 support along the way.

We started beta-testing a whole new set of features to be released early next year: a new unit testing framework, a heap profiler, integrating MonoTouch.Dialog in the product and improving the debug/deploy process.<

Mono for iOS has been on the market now for two years, and many products are coming to the market based on it.

Phalanger

Phalanger is a PHP compiler that runs on the .NET and Mono VMs and is powered by the Dynamic Language Runtime.

It is so complete that it can run both MediaWiki and WordPress out of the box. And does so by running faster than they would under PHP.

This year the Phalanger guys released Phalanger 3.0 which now runs on Mono (previously they required the C++/CLI compiler to run).

Phalanger's performance is impressive as it is just as fast as the newly announced Facebook HipHop VM for PHP. The major difference being that Phalanger is a complete PHP implementation and the HipHopVM is still not a complete implementation.

The other benefit of Phalanger is that it is able to participate and interop with code written in other .NET languages as well as benefitting from the existing .NET interop story (C, C++).

CXXI

Our technology to bridge C# and C++ matured to the point that it can be used by regular users.

Compiler as a Service

This year our C# compiler was expanded in three directions:

  • We completed async/await support
  • We completed the two code output engines (System.Reflection.Emit and IKVM.Reflection).
  • We improved the compiler-as-a-service features of the compiler.

Our async/await support is scheduled to go out with the first preview of Mono 2.11 in early January. We can not wait to get this functionality to our users and start building a new generation of async-friendly/ready desktop, mobile and server apps.

One major difference between our compiler-as-a-service and Microsoft's version of the C# compiler as a service is that we support two code generation engines, one generates complete assemblies (like Microsoft does) and the other one is able to be integrated with running code (this is possible because we use System.Reflection.Emit and we can reference static or dynamic code from the running process).

We have also been improving the error recovery components of the compiler as this is going to power our new intellisense/code completion engine in MonoDevelop. Mono's C# compiler is the engine that is powering the upcoming NRefactory2 library.

You can read more about our compiler as a service updates.

Unity3D

Unity is one of Mono's major users. At this point Unity no longer requires an introduction, they went from independent game engine a few years ago to be one of the major game engine platforms in the game industry this year.

The Unity engine runs on every platform under the sun. From the Consoles (PS3, Wii and XBox360) to iPhones and Androids and runs on your desktop either with the Unity3D plugin or using Google's Native Client technology. The list of games being built with Unity keeps growing every day and they are consistently among the top sellers on every app store.

Mono is the engine that powers the scripts and custom code in games and applications built with Unity3D and it also powers the actual tool that users use to build games, the Unity3D editor:

The editor itself it implemented in terms of Unity primitives, and users can extend the Unity3D editor with C#, UnityScript or Boo scripts dynamically.

One of my favorite games built with Unity3D is Rochard was demoed earlier this year on a PS3 at the GDC and is now also avaialble on Steam:

Microsoft

Just before the end of the year, Microsoft shipped Kinectimals for iOS systems.

Kinectimals is built using Unity and this marks the first time that Microsoft ships a software product built with Mono.

Then again, this year has been an interesting year for Microsoft, as they have embraced open source technologies for Azure, released SDKs for iOS and Android at the same time they ship SDKs for their own platforms and shipped various applications on Apple's AppStore for iOS.

MonoDevelop

We started the year with MonoDevelop 2.4 and we finished after two major releases with MonoDevelop 2.8.5.

In the course of the year, we added:

  • Native Git support
  • Added .NET 4.0 project support, upgraded where possible to XBuild/MSBuild
  • MonoMac Projects
  • XCode 4 support for MonoMac, MonoTouch and Storyboards
  • Support for Android development
  • Support for iOS5 style properties
  • Major upgrade to the debugger engine
  • Adopted native dialogs on OSX and Windows

Our Git support was based on a machine assisted translation of the Java jGit library using Sharpen. Sharpen has proved to be an incredibly useful tool to bring Java code to the .NET world.

SGen

Our precise collector has gotten a full year of testing now. With Mono 2.10 we made it very easy for developers to try it out. All users had to do was run their programs with the --sgen flag, or set MONO_ENV_OPTIONS to gc=sgen.

Some of the new features in our new Garbage Collector include:

  • Windows, MacOS X and S390x ports of SGen (in addition to the existing x86, x86-64 and ARM ports).
  • Lock-free allocation to improve scalability (we only take locks when we run out of memory).
  • Work stealing parallel collector and a parallel nursery collector, to take advantage of extra CPUs on the system to help with the GC.
  • Work on performance and scalability work, as our users tried things out in the field, we identified hot-spots in SGen which we have been addressing.

As we are spending so much time on ARM-land these days, SGen has also gained various ARM-specific optimizations.

SGen was designed primarly to be used by Mono and we are extending it beyond being a pure garbage collector for Mono, to support scenarios where our garbage collector has to be integrated with other object systems and garbage collectors. This is the case of Mono for Android where we now have a cooperative garbage collector that works hand-in-hand with Dalvik's GC. And we also introduce support for toggle references to better support Objective-C environments like MonoTouch and MonoMac.

XNA and Mono: MonoGame

Ever since Microsoft published the XNA APIs for .NET, developers have been interested in bringing XNA to Mono-based platforms.

There was a MonoXNA project, which was later reused by projects like SilverXNA (an XNA implementation for Silverlight) and later XNAtouch an implementation of XNA for the iPhone powered by MonoTouch. Both very narrow projects focused on single platforms.

This year, the community got together and turned the single platform XNATouch into a full cross-platform framework, the result is the MonoGame project:

Platform Support Matrix

Currently MonoGame's strength is on building 2D games. They already have an extensive list of games that have been published on the iOS AppStore and the Mac AppStore and they were recently featured in Channel 9's Coding For Fun: MonoGame Write Once Play Everywhere.

An early version of MonoGame/XnaTouch powers SuperGiantGame's Bastion game on Google's Native Client. Which allows users of Windows, Mac and Linux desktop systems to run the same executable on all systems. If you are running Chrome, you can install it in seconds.

Incidentally, Bastion just won three awards at the Spike VGA awards including Best Downloadable Game, Best Indie Game, and Best Original Score.

The MonoGame team had been relatively quiet for the most part of 2011 as they were building their platform, but they got into a good release cadence with the MonoGame 2.0 release in October, when they launched as a cross-platform engine, followed up with a tasty 2.1 release only two weeks ago.

With the addition of OpenGL ES 2.0 support and 3D capabilities to MonoGame, 2012 looks like it will be a great year for the project.

Gtk+

Since MonoDevelop is built on top of the Gtk+ toolkit and since it was primarily a Unix toolkit there have been a few rough areas for our users in both Mac and Windows.

This year we started working with the amazing team at Lanedo to improve Gtk+ 2.x to work better on Mac and Windows.

The results are looking great and we want to encourage developers to try out our new Beta version of Mono, which features the updated Gtk+ stack.

This new Gtk+ stack solves many of the problems that our users have reported over the past few months.

Hosting Bills

I never tracked Mono downloads as I always felt that tracking download numbers for open source code that got repackaged and redistributed elsewhere pointless.

This summer we moved the code hosting from Novell to Xamarin and we were surprised by our hosting bills.

The major dominating force are binaries for Windows and MacOS which are communities that tend not to download source and package the software themselves. This is the breakdown for completed downloads (not partial downloads, or interrupted ones) for our first month of hosting of Mono:

  • 39,646 - Mono for Windows (Runtime + SDK)
  • 27,491 - Mono for Mac (Runtime)
  • 9,803 - Mono for Windows (Runtime)
  • 9,910 - Mono for Mac (Runtime + SDK)

  • Total: 86,850 downloads for Windows and Mac

These numbers are only for the Mono runtime, not MonoDevelop, the MonoDevelop add-ins or any other third party software.

It is also worth pointing out that none of our Windows products (MonoDevelop for Windows, or Mono for Android on Windows) use the Mono runtime. So these downloads are for people doing some sort of embedding of Mono on their applications on Windows.

At this point, we got curious. We ran a survey for two days and collected 3,949 answers. These is the summary of the answers:

What type of application will you run with Mono?

This one was fascinating, many new users to the .NET world:

The best results came form the free-form answers in the form. I am still trying to figure out how to summarize these answers, they are all very interesting, but they are also all over the map.

Some Key Quotes

When I asked last week for stories of how you used Mono in 2011, some of you posted on the thread, and some of you emailed me.

Here are a couple of quotes from Mono users:

I can't do without Mono and I don't just mean the iOS or Android dev with C# but MonoMac and Mono for *nix too. Thanks for everything; from the extraordinary tools to making hell turn into heaven, and thank you for making what used to be a predicament to effortless development pleasure.

I don't think we could have achieved our solutions without Mono in enterprise mobile development. It addresses so many key points, it is almost a trade secret. We extensively use AIR and JavaScript mobile frameworks too but ultimately we desperately need 1-to-1 mapping of the Cocoa Touch APIs or tap into low level features which determines our choice of development platform and frameworks.

That's where Mono comes in.

Gratefulness and paying polite respects aside, the key tenets of Mono we use are:

  • shared C# code base for all our enterprise solutions - achieving the write once, compile everywhere promise with modern language and VM features everyone demands and expects in this century
  • logical, consistent and self-explanatory wrapper APIs for native services - allows us to write meta APIs of our own across platforms
  • low latency, low overhead framework
  • professional grade IDE and tools
  • native integration with iOS tools and development workflow
  • existence of satisfactory documentation and support
  • legal clarity - favorable licensing options
  • dedicated product vision via Xamarin - commercial backing
  • community support

Koen Pijnenburg shared this story with me:

We've been in touch a few times before and would like to contribute my story. It's not really an interesting setup, but a real nice development for Mono(Touch). I've been developing app for iPhone since day 1, I was accepted in the early beta for the App Store. On launch day july 2008, 2 of the 500 apps in the App Store were mine, my share has decreased a lot in the past years ;)

I really, really, really like football(soccer), maybe you do also, I don't know. In september 2008 I created the first real soccer/football stats app for the iPhone called My Football. This was a huge succes, basically no competition at that time. In 2009 I released My Football Pro, an app with 800 leagues worldwide, including live data for more then 100 leagues. Since then I created lots of apps, all created with the iPhone SDK and with Objective-C.

Since the launch of MonoTouch, it merged the best of two worlds in my opinion. I've been a Mono/.NET developer for years before the iPhone apps, for me it was love at first line of code.

The last year I've increased my work with MonoTouch / Droid /MonoGame(Poppin' Frenzy etc ;)), and focused less on working with native SDK's only. Since our My Football apps are at the end of their lifecycle in this form, we are working on a new line of My Football apps. Our base framework supporting our data, is built with Mono, and the apps UI will be built with MonoTouch / MonoDroid / WP7 etc.

Included is the screenshot of our first app built with the framework, My Football Pro for iPad. It has a huge amount of data, stats / tables / matches / live data for more then 800 leagues worldwide. We think it's a great looking app!

Working with MonoTouch is fantastic and just wanted you to know this!

Mono on Mainframes

This year turned out to show a nice growh in the deployment of Mono for IBM zSeries computers.

Some are using ASP.NET, some are using Mono in headless mode. This was something that we were advocating a few years ago, and this year the deployments went live both in Brazil and Europe.

Neale Ferguson from Sinenomine has kept the zSeries port active and in shape.

Mono and ASP.NET

This year we delivered enough of ASP.NET 4.0 to run Microsoft's ASP.NET MVC 3.

Microsoft ASP.NET MVC 3 is a strange beast. It is licensed under a great open source license (MS-PL) but the distribution includes a number of binary blobs (the Razor engine).

I am inclined to think that the binaries are not under the MS-PL, but strictly speaking, since the binaries are part of the MS-PL distribution labeled as such, the entire download is MS-PL.

That being said, we played it safe in Mono-land and we did not bundle ASP.NET MVC3 with Mono. Instead, we provide instructions on how users can deploy ASP.NET MVC 3 applications using Razor as well as pure Razor apps (those with .cshtml extensions) with Mono.

2012, the year of Mono 2.12

2012 will be a year dominated by our upcoming Mono release: Mono 2.12. It packs a year worth of improvements to the runtime, to our build process and to the API profiles.

Mono 2.12 defaults to the .NET 4.x APIs and include support for .NET 4.5.

This is going to be the last time that we branch Mono for these extended periods of time. We are changing our development process and release policies to reduce the amount of code that is waiting on a warehouse to be rolled out to developers.

ECMA

We wrapped up our work on updating the ECMA CLI standard this year. The resulting standard is now at ISO and going through the standard motions to become an official ISO standard.

The committee is getting ready for a juicy year ahead of us where we are shifting gears from polish/details to take on significant extensions to the spec.

Posted on 21 Dec 2011


CXXI: Bridging the C++ and C# worlds.

by Miguel de Icaza

The Mono runtime engine has many language interoperability features but has never had a strong story to interop with C++.

Thanks to the work of Alex Corrado, Andreia Gaita and Zoltan Varga, this is about to change.

The short story is that the new CXXI technology allows C#/.NET developers to:

  • Easily consume existing C++ classes from C# or any other .NET language
  • Instantiate C++ objects from C#
  • Invoke C++ methods in C++ classes from C# code
  • Invoke C++ inline methods from C# code (provided your library is compiled with -fkeep-inline-functions or that you provide a surrogate library)
  • Subclass C++ classes from C#
  • Override C++ methods with C# methods
  • Expose instances of C++ classes or mixed C++/C# classes to both C# code and C++ as if they were native code.

CXXI is the result of two summers of work from Google's Summer of Code towards improving the interoperability of Mono with the C++ language.

The Alternatives

This section is merely a refresher of of the underlying technologies for interoperability supported by Mono and how developers coped with C++ and C# interoperability in the past. You can skip it if you want to get to how to get started with CXXI.

As a reminder, Mono provides a number of interoperability bridges, mostly inherited from the ECMA standard. These bridges include:

  • The bi-directional "Platform Invoke" technology (P/Invoke) which allows managed code (C#) to call methods in native libraries as well as support for native libraries to call back into managed code.
  • COM Interop which allows Mono code to transparently call C or C++ code defined in native libraries as long as the code in the native libraries follows a few COM conventions [1].
  • A general interceptor technology that can be used to intercept method invocations on objects.

When it came to getting C# to consume C++ objects the choices were far from great. For example, consider a sample C++ class that you wanted to consume from C#:

class MessageLogger {
public:
	MessageLogger (const char *domain);
	void LogMessage (const char *msg);
}

One option to expose the above to C# would be to wrap the Demo class in a COM object. This might work for some high-level objects, but it is a fairly repetitive exercise and also one that is devoid of any fun. You can see how this looks like in the COM Interop page.

The other option was to produce a C file that was C callable, and invoke those C methods. For the above constructor and method you would end up with something like this in C:

/* bridge.cpp, compile into bridge.so */
MessageLogger *Construct_MessageLogger (const char *msg)
{
	return new MessageLogger (msg);
}

void LogMessage (MessageLogger *logger, const char *msg)
{
	logger->LogMessage (msg);
}

And your C# bridge, like this:

class MessageLogger {
	IntPtr handle;

	[DllImport ("bridge")]
	extern static IntPtr Construct_MessageLogger (string msg);

	public MessageLogger (string msg)
	{
		handle = Construct_MessageLogger (msg);
	}

	[DllImport ("bridge")]
	extern static void LogMessage (IntPtr handle, string msg);

	public void LogMessage (string msg)
	{
		LogMessage (handle, msg);
	}
}

This gets tedious very quickly.

Our PhyreEngine# binding was a C# binding to Sony's PhyreEngine C++ API. The code got very tedious, so we built a poor man's code generator for it.

To make things worse, the above does not even support overriding C++ classes with C# methods. Doing so would require a whole load of manual code, special cases and callbacks. The code quickly becomes very hard to maintain (as we found out ourselves with PhyreEngine).

This is what drove the motivation to build CXXI.

[1] The conventions that allow Mono to call unmanaged code via its COM interface are simple: a standard vtable layout, the implementation of the Add, Release and QueryInterface methods and using a well defined set of types that are marshaled between managed code and the COM world.

How CXXI Works

Accessing C++ methods poses several challenges. Here is a summary of the components that play a major role in CXXI:

  • Object Layout: this is the binary layout of the object in memory. This will vary from platform to platform.
  • VTable Layout: this is the binary layout that the C++ compiler will use for a given class based on the base classes and their virtual methods.
  • Mangled names: non-virtual methods do not enter an object vtable, instead these methods are merely turned into regular C functions. The name of the C functions is computed based on the return type and the parameter types of the method. These vary from compiler to compiler.

For example, given this C++ class definition, with its corresponding implementation:

class Widget {
public:
	void SetVisible (bool visible);
	virtual void Layout ();
	virtual void Draw ();
};

class Label : public Widget {
public:
	void SetText (const char *text);
	const char *GetText ();
};

The C++ compiler on my system will generate the following mangled names for the SetVisble, Layout, Draw, SetText and GetText methods:

__ZN6Widget10SetVisibleEb
__ZN6Widget6LayoutEv
__ZN6Widget4DrawEv
__ZN5Label7SetTextEPKc
__ZN5Label7GetTextEv

The following C++ code:

	Label *l = new Label ();
	l->SetText ("foo");
	l->Draw ();	

Is roughly compiled into this (rendered as C code):

	Label *l = (Label *) malloc (sizeof (Label));
	ZN5LabelC1Ev (l);   // Mangled name for the Label's constructor
	_ZN5Label7SetTextEPKc (l, "foo");

	// This one calls draw
	(l->vtable [METHOD_PTR_SIZE*2])();

For CXXI to support these scenarios, it needs to know the exact layout for the vtable, to know where each method lives and it needs to know how to access a given method based on their mangled name.

The following chart explains shows how a native C++ library is exposed to C# or other .NET languages:

Your C++ source code is compiled twice. Once with the native C++ compiler to generate your native library, and once with the CXXI toolchain.

Technically, CXXI only needs the header files for your C++ project, and only the header files for the APIs that you are interested in wrapping. This means that you can create bindings for C++ libraries that you do not have the source code to, but have its header files.

The CXXI toolchain produces a .NET library that you can consume from C# or other .NET languages. This library exposes a C# class that has the following properties:

  • When you instantiate the C# class, it actually instantiates the underlying C++ class.
  • The resulting class can be used as the base class for other C# classes. Any methods flagged as virtual can be overwritten from C#.
  • Supports C++ multiple inheritance: The generated C# classes expose a number of cast operators that you can use to access the different C++ base classes.
  • Overwritten methods can call use the "base" C# keyword to invoke the base class implementation of the given method in C++.
  • You can override any of the virtual methods from classes that support multiple inheritance.
  • A convenience constructor is also provided if you want to instantiate a C# peer for an existing C++ instance that you surfaced through some other mean.

This is pure gold.

The CXXI pipeline in turn is made up of three components, as shown in the diagram on the right.

The GCC-XML compiler is used to parse your source code and extract the vtable layout information. The generated XML information is then processed by the CXXI tooling to generate a set of partial C# classes that contain the bridge code to integrate with C++.

This is then combined with any customization code that you might want to add (for example, you can add some overloads to improve the API, add a ToString() implementation, add some async front-ends or dynamic helper methods).

The result is the managed assembly that interfaces with the native static library.

It is important to note that the resulting assembly (Foo.dll) does not encode the actual in-memory layout of the fields in an object. Instead, the CXXI binder determines based on the ABI being used what the layout rules for the object are. This means that the Foo.dll is compiled only once and could be used across multiple platforms that have different rules for laying out the fields in memory.

Demos

The code on GitHub contains various test cases as well as a couple of examples. One of the samples is a minimal binding to the Qt stack.

Future Work

CXXI is not finished, but it is a strong foundation to drastically improve the interoperability between .NET managed languages and C++.

Currently CXXI achieves all of its work at runtime by using System.Reflection.Emit to generate the bridges on demand. This is useful as it can dynamically detect the ABI used by a C++ compiler.

One of the projects that we are interested in doing is to add support for static compilation, this would allow PS3 and iPhone users to use this technology. It would mean that the resulting library would be tied to the platform on which the CXXI tooling was used.

CXXI currently implements support for the GCC ABI, and has some early support for the MSVC ABI. Support for other compiler ABIs as well as for completing the MSVC ABI is something that we would like help with.

Currently CXXI only supports deleting objects that were instantiated from managed code. Other objects are assumed to be owned by the unmanaged world. Support for the delete operator is something that would be useful.

We also want to better document the pipeline, the runtime APIs and improve the binding.

Posted on 19 Dec 2011


2011: Tell me how you used Mono this year

by Miguel de Icaza

I have written a summary of Mono's progress in the year 2011, but I want to complement my post with stories from the community.

Did you use Mono in an interesting setup during 2011? Please post a comment on this post, or email me the story and tell me a little bit about it.

Posted on 15 Dec 2011


Porto Alegre

by Miguel de Icaza

We are traveling to Porto Alegre in Brazil today and will be staying in Brazil until January 4th.

Ping me by email (miguel at gnome dot org) if you would like to meet in Porto Alegre to talk hacking, Mono, Linux, open source, iPhone or if you want to enlighten me about the role of scrum masters as actors of social change.

Happy holidays!

Posted on 14 Dec 2011


Farewell to Google's CodeSearch

by Miguel de Icaza

It seems that part of Steve Jobs' legacy was to give Larry Page some advise: focus. This according to Steve Jobs' recently published biography.

So Larry Page took the advise seriously and decided to focus. His brand of focus is to kill projects that were distracting to their goals. One of them, -and the one I cared the most about- was CodeSearch..

What did CodeSearch do for programmers?

The CodeSearch service was a unique tool as it indexed open source code in the wild.

Codesearch is one of the most valuable tools in existence for all software developers, specifically:

  • When an API is poorly documented, you could find sample bits of code that used the API.
  • When an API error codes was poorly documented, you could find sample bits of code that handled it.
  • When an API was difficult to use (and the world is packed with those), you could find sample bits of code that used it.
  • When you quickly wanted to learn a language, you knew you could find quality code with simple searches.
  • When you wanted to find different solutions to everyday problems dealing with protocols, new specifications, evolving standards and trends. You could turn to CodeSearch.
  • When you were faced with an obscure error message, an obscure token, an obscure return value or other forms of poor coding, you would find sample bits of code that solved this problem.
  • When dealing with proprietary protocols or just poorly documented protocols, you could find how they worked in minutes.
  • When you were trying to debug yet another broken standard or yet another poorly specified standard, you knew you could turn quickly to CodeSearch to find the answers to your problems (memories of OAuth and IMAP flash in my head).
  • When learning a new programming language or trying to improve your skills on a new programming language, you could use CodeSearch to learn the idioms and the best (and worst practices).
  • When building a new version of a library, either in a new language, making a fluent version, making an open source version, building a more complete version you would just go to Codesearch to find answers to how other people did things.

It is a shame that Google is turning their back on their officially stated mission "To organize the world‘s information and make it universally accessible and useful". It is a shame that this noble goal is not as important as competing with Apple, Facebook, Microsoft, Twitter and Yelp.

Comparing Search Engines

While writing this blog entry, I fondly remembered how Codesearch helped me understand the horrible Security framework that ships with iOS. Nobody informed the Apple engineers that "Security through obscurity" was not intended for their developer documentation.

In this particular case, I was trying to understand the semantics of kSecReturnData. How to use this constant and how it interacts with the keyring system is both tricky, and poorly specified in Apple's docs. Sometimes things fail without any indication of what went wrong, other than "error". So I used CodeSearch to figure this out (along with some other 30 constants and APIs in that library that are just as poorly documented).

These are the results of looking for this value in three search engines as of this morning.

First Contender: GrepCode

GrepCode shows absolutely nothing relevant. But shows a bunch of Java packages with no context, no code snippets and if you make the mistake of drilling down, you wont find anything:

Not useful.

Second Contender: Codease

Codase is indexing 250 million lines of code, usually it takes minutes to get this page:

Maybe the server will come back up.

Third Contender: Koders

Koders is part of Black Duck, and searching for the term renders a bunch of matches. Not a single one of the results displayed actually contain a single use of the kSecReturnData constant. And not a single one of the snippets actually show the kSecReturnData constant. It is as useful as configuring your browser to use StumbleUpon as your search engine:

Not useful.

Google's CodeSearch

And this is what Codesearch shows:

The big innovation on Google's search engine is that it actually works and shows real matches for the text being searched, with a relevant snippet of the information you are looking for.

We are going to be entering the dark ages of software research in the next few months.

Is there a hacker White Knight out there?

Running a service like Codesearch is going to take a tremendous amount of resources. There are major engineering challenges involved and hosting a service like this can not be cheap. It is probably not even profitable.

Larry Page's Google has already dropped the project. We can only hope that in a few years Sergey Brin's Google or Eric Schmidt's Google will bring this service back.

Microsoft is too busy catching up to Google and wont have any spare resources to provide a Bing for code search. And if they did, they would limit the search to Win32 APIs.

Thanks!

I should thank Google for funding that project for as long as they did as well as the Google engineers that worked on it as long as they could. Over the years, it helped me fix problems in a fraction of the time and helped me understand complicated problems in minutes.

The Google engineers whose projects just got shutdown for in the name of strategy and focus are probably as sad as all of us are.

On the plus side, I get to share this rant on Google Plus with a dozen of my friends!

Posted on 29 Nov 2011


« Newer entries | Older entries »