Generally I agree with @Clonk. Much happier to wrap C libs and live in Nim.

However, sometimes that's not an option and you gotta live in a C world and 
export a C API. You should checkout @treeform's [Genny 
project](https://github.com/treeform/genny).

Really you only need to change `newCStruct` to return the struct. Nim 
constructors are really just functions that return an initialized value. Though 
you could use a `initMyStruct(item: var Mod)` as well. Also, sometimes you 
need/want to add a `bycopy` pragma on you `Mod` import.

Also, to get some C type checking can do things like the below. Though I make 
no guarantees. ;) Genny looks much saner to me. There are probably other 
options too.

Find you exportc function in the nimcache output folder. Then copy the 
declaration like so:
    
    
    #include "mod.h"
    #include "stdio.h"
    
    #define NIM_INTBITS 64
    #include "nims/nimbase.h"
    N_NIMCALL(struct Mod, newCStruct)(NF32 x, NI32 y);
    
    int main() {
      // ...
      Mod m2 = newCStruct(10.0, 20);
      // ...
    }
    
    
    Run
    
    
    nim c --gc:arc --compileOnly --noMain --nimcache:nims/ ffi.nim
    cp $NIM_COMPILER/lib/nimbase.h nims/
    gcc main.c nims/*.c
    
    
    Run

Reply via email to