Search code examples
ffinim-lang

Nim import typedef from C header file


I'm wondering if I can import a C type definition or if I need to redefine it in Nim?

Looking at program called jhead interfacing with this proc

int ReadJpegFile(const char * FileName, ReadMode_t ReadMode);

The second parameter ReadMode_t is an enum type in jhead.h

typedef enum {
    READ_METADATA = 1,
    READ_IMAGE = 2,
    READ_ALL = 3,
    READ_ANY = 5        // Don't abort on non-jpeg files.
}ReadMode_t;

Can I import this ReadMode_t? Or do I have to redfine it like below

type
  ReadMode_t* = enum
    READ_METADATA = 1, READ_IMAGE = 2, READ_ALL = 3, READ_ANY = 5

Solution

  • The Nim compiler needs to know about those C constants, so you have to define them to use them from Nim. However, this tedious copying can be simplified and even automated to some degree with tools like c2nim. In fact, if you take the following test.h file:

    typedef enum {
        READ_METADATA = 1,
        READ_IMAGE = 2,
        READ_ALL = 3,
        READ_ANY = 5        // Don't abort on non-jpeg files.
    }ReadMode_t;
    
    int ReadJpegFile(const char * FileName, ReadMode_t ReadMode);
    

    and run c2nim test.h, it will generate the following test.nim file for you, saving most of the tedious translation:

    type
      ReadMode_t* = enum
        READ_METADATA = 1, READ_IMAGE = 2, READ_ALL = 3, READ_ANY = 5
    
    
    proc ReadJpegFile*(FileName: cstring; ReadMode: ReadMode_t): cint