Creating .NET Bindings for C Libraries with ObjectiveSharpie

by Miguel de Icaza

We created the ObjectiveSharpie tool to automate the mapping of Objective-C APIs to the .NET world. This is the tool that we use to keep up with Apple APIs.

One of the lesser known features of ObjectiveSharpie, is that it is not limited to binding Objective-C header files. It is also capable of creating definitions for C APIs.

To do this, merely use the "bind" command for ObjectiveSharpie and run it on the header file for the API that you want to bind:

	sharpie bind c-api.h -o binding.cs

The above command will produce the binding.cs that contains the C# definitions for both the native data structures and the C functions that can be invoked.

Since C APIs are ambiguous, in some cases ObjectiveSharpie will generate some diagnostics. In most cases it will flag methods that have to be bound with the [Verify]. This attribute is used as an indicator on your source code that you need to manually audit the binding, perhaps checking the documentation and adjust the P/Invoke signature accordingly.

There are various options that you can pass to the bind command, just invoke sharpie bind to get an up-to-date list of configuration options.

This is how I quickly bootstrapped the TensorFlowSharp binding. I got all the P/Invoke signatures done in one go, and then I started to do the work to surface an idiomatic C# API.

Posted on 18 Jan 2017