Thanks from a python programmer

mipri mipri at minimaltype.com
Fri Mar 5 06:11:33 UTC 2021


On Friday, 5 March 2021 at 02:13:44 UTC, James Lu wrote:
> On Thursday, 4 March 2021 at 20:14:32 UTC, Curious George wrote:
>>
>> I know this might be construed as rude to say this on D's NG, 
>> but have you checked out nim? It has python-like syntax, can 
>> compile directly to C, and thus utilize such libraries and 
>> code easier than D can. It's also a growing language.
>
> Python has first-class C integration, and D has first-class 
> extern(C) support.

Here's a complete Nim program that prints the max amount of
file descriptors that a select() set can have:

   let FD_SETSIZE {.importc: "FD_SETSIZE", header: 
"<sys/select.h>".}: cint
   echo FD_SETSIZE

Here's a version that exports a function that returns that
value:

   let FD_SETSIZE* {.importc: "FD_SETSIZE", header: 
"<sys/select.h>".}: cint
   proc setsize*: cint {.exportc.} = FD_SETSIZE

With this assembly:

   setsize:
    endbr64
    mov    eax,0x400
    ret
    nop    WORD PTR [rax+rax*1+0x0]

So FD_SETSIZE is 1024 on godbolt.org. There's no 1024 in the
Nim, and Nim is not parsing the C headers or anything; it's
just deferring the value to C.

This is a nice thing you get from a transpiler... which nobody
using Nim really exploits, preferring to put a bunch of Nim
const definitions with what the C headers have. Anyway, here's
some more very uncommon Nim:

   proc `*`(a: float, b: int64): float =
      {.emit: [result, " = ", a, " * ", b, ";"].}

That's a * operator that literally just returns whatever a*b
does with those types in C.

That's first class C integration. Here's business class from
Zig:

   const c = @cImport({
       @cDefine("_NO_CRT_STDIO_INLINE", "1");
       @cInclude("stdio.h");
   });
   pub fn main() void {
       _ = c.printf("hello\n");
   }

This sets a C #define and then includes everything from stdio.h
as a struct with #defines as variables, C functions as Zig
functions, C #define *macros* also as Zig functions, etc. This
time the magic is not from C codegen and deferring the work to
a C compiler, but from Zig's compiler properly digesting C's
header files.

What D has is very fine, but it's general seating. Any language
with an FFI at all should be about as capable as D's FFI.

The last time I did C FFI with Python it was such a chore that
http://swig.org/ happened to pull the Python programmers off
the wings and actually into the airplane. I guess it's gotten
much better.



More information about the Digitalmars-d mailing list