Interfacing C functions with safer ptr/length

bearophile bearophileHUGS at lycos.com
Fri Oct 29 19:11:04 PDT 2010


I am toying with more ideas to strengthen D type system a bit in few spots. This is a minor thing, I don't know if this is a common enough situation to deserve compiler support, maybe not.

If I want to use a C function from D code, and such C function has as arguments both a pointer that represents an array and int value that represents its length, is it possible to use a compact syntax that tells the compiler how to pack or unpack the contents of the fat D pointer that represents a D array?

Something like this:

extern(C) void foo(int[].ptr, int, int[].length);

If the function needs two or more arrays the compiler asks you to give names to tell apart their parts in the signature:

extern(C) void bar(int[].ptr a1, int[].length a1, int[].ptr a2, int[].length a2);

This is supposed to avoid some bugs in using from D with dynamic arrays those functions foo() and bar().

So you have to call foo() like this:

foo(v.ptr, n, v.length);

While this generates a compile-time error because here the D code calls this function with parts from different arrays:

foo(v1.ptr, n, v2.length);

This too generates compile-time errors because m isn't the length of v1 and p isn't the ptr of v2:

foo(v1.ptr, n, m);
foo(p, n, v2.length);

(This idea was born from reading about Deputy, a system to build safer Linux drivers.) I am trying to invent ideas better than this one.

Bye,
bearophile


More information about the Digitalmars-d mailing list