Using Couchbase from Delphi

TL;DR: Expose the Couchbase .NET SDK through COM interop by wrapping it in a simple facade class.

I got an unusual request today: a prospective Couchbase customer wants to use the database from a Delphi application. Turns out Delphi is still a thing! Who knew?

As it happens, it's actually quite simple to use the Couchbase .NET SDK from Delphi by wrapping it in a slim facade class and exposing said facade through COM interop.

We start by creating a regular .NET class library project and adding a NuGet reference to the Couchbase SDK. Next we add interface we're going to expose through COM to the class library:

public interface ICouchbaseFacade
    object Get(string key);
    void Upsert(string key, object value);

And the class that implements said interface:

public class CouchbaseFacade : ICouchbaseFacade
    // ...

Since this is just a POC, we're not going to do anything fancy in the facade class. Just open a connection to the 'default' bucket on localhost in the constructor, and implement a couple of simple methods to demonstrate CRUD operations.

    private IBucket _bucket;
    private Cluster _cluster;

    public CouchbaseFacade()
        _cluster = new Cluster();
        _bucket = _cluster.OpenBucket("default");

    public object Get(string key)
        return _bucket.Get<object>(key).Value;

    public void Upsert(string key, object value)
        _bucket.Upsert(key, value);

Next, let's build the project and register the assembly for COM interop. Either check the "Register for COM interop" box in the Build tab of the project properties, or run regasm /codebase /tlb <path to DLL> from the command-line. Either option requires administrator privileges to work.

With that done, it's time to use our new SDK wrapper from Delphi. Create a new Delphi project and then click "Import Component" under the Component menu. Select "Import Type Libray" and find the .NET assembly we exported as COM earlier. Import the library, which will add the ICouchbaseFacade interface and CoCouchbaseFacade classes to your Delphi project. All that's left is to create an instance of the class and try out the Upsert and Get methods we added earlier:


  Couchbase: ICouchbaseFacade;

// ...

Couchbase := CoCouchbaseFacade.Create;
Couchbase.Upsert('_test', 'hello world!');
ShowMessage('Result: ' + Couchbase.Get('_test'));

If all goes well, this will create a new document with the key "_test" and the value "hello world!".

Then retrieve it and show the result in a message box.

You can get the complete POC code here:

David Ostrovsky

I'm a level 38 Computer Geek, with experience in everything from databases to mobile apps. I'm also a Senior Solutions Architect at Couchbase, where I often keep clients happy by coding hard.

comments powered by Disqus