valavapi

Implicitly pass instance in vapi


I am trying to write a VAPI for the mongoc library.

I have created some compact classes from struct with some functions associated with them. For example Client looks like this:

[Compact]
[CCode (cname = "mongoc_client_t", free_function = "mongoc_client_destroy", has_type_id = false)]
public class Client {

   [CCode (cname = "mongoc_client_new")]
   public Client (string uri);
}

I need to bind also a bunch of the related functions. I tried to bind them as instance methods, like this:

[CCode (cname = "mongoc_client_get_database")]
public Database get_database (Client client, string dbname);
//Database is another compact class

So that the resulting is this:

[CCode (cheader_filename = "mongoc.h")]
namespace Mongo {
   [Compact]
   [CCode (cname = "mongoc_client_t", free_function = "mongoc_client_destroy", has_type_id = false)]
   public class Client {

      [CCode (cname = "mongoc_client_new")]
      public Client (string uri);

      [CCode (cname = "mongoc_client_get_database")]
      public Database get_database (Client client, string dbname);
   }
}

I wanted it to take the first client parameter as the calling instance. Instead of this:

var client = new Client ("uri");
var db = client.get_database (client, "test");
//client is redundant

Im trying to get this:

var client = new Client ("uri");
var db = client.get_database ("test");
//The Client instance is passed implicitly

I tried using this, static methods, instance_pos and other tweaks but I didn't find a way to get it working in that way.

Is it possible to pass the instance implicitly as a parameter in Vala? If so, how can I bind a VAPI in a way that the instance is passed implicitly without redundancy?


Solution

  • The C API for mongoc_client_get_database() shows the function signature is:

    mongoc_database_t * mongoc_client_get_database (mongoc_client_t *client, const char *name);

    So the monogc_client_t is passed explicitly in the C API. In Vala this is automatically generated as the instance argument in the C code. You just need to drop the explicit argument, Client client, from the VAPI:

    [CCode (cheader_filename = "mongoc.h")]
    namespace Mongo {
       [Compact]
       [CCode (cname = "mongoc_client_t", free_function = "mongoc_client_destroy", has_type_id = false)]
       public class Client {
    
          [CCode (cname = "mongoc_client_new")]
          public Client (string uri);
    
          [CCode (cname = "mongoc_client_get_database")]
          public Database get_database (string dbname);
       }
    }