jython234 jython234 - 8 months ago 29
C Question

Array pointer from C to D

I'm using D and interfacing with some C libraries. As a result I have to convert D arrays to pointers for C (ex. short*). Currently I just cast them like this:

int[] dArray = [0, 1, 2, 3, 4];
myCFunction(cast(int*) dArray);

Is this unsafe? I tried to do:


But doing that gives the function an int[]* instead of int*. I see that in C++ some people take the first element like this:


But wouldn't that pointer only point to the first element? I am new to pointers and references as I have come from the world of Java.

How would I convert an array to a pointer so I can pass it to a C function?


In D, an array is actually (conceptually) this:

struct {
    size_t length;
    void* ptr;

The usual way of getting a pointer from an array is to use the .ptr field. In your case: myCFunction(dArray.ptr);

But wouldn't that pointer only point to the first element

Because the elements are stored contiguously in memory, a pointer to the first element is all we need. We just add an offset to that pointer if we want to get the addresses of other elements.

One other point: usually if a C function wants an array pointer, it also has an argument for the array length. In most cases you can give it dArray.length, but sometimes it's actually asking for the size in bytes, rather than the number of elements.