Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array pointer from C to D

Tags:

arrays

c

pointers

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:

myCFunction(&dArray);

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

myCFunction(&dArray[0]);

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?

like image 387
jython234 Avatar asked Aug 22 '16 21:08

jython234


People also ask

How do you assign a pointer to a 2D array?

Get the element => *( (int *)aiData + offset ); calculate offset => offset = (1 * coloumb_number)+ 2); Add offset in array base address => (int *)aiData + offset; //here typecast with int pointer because aiData is an array of integer Get the element => *( (int *)aiData + offset );

How do I declare a pointer to an array in C?

Unary operator ( * ) is used to declare a variable and it returns the address of the allocated memory. Pointers to an array points the address of memory block of an array variable. The following is the syntax of array pointers. datatype *variable_name[size];

How is a pointer in C related to one dimensional array?

The name or identifier of an array is itself a constant pointer to the array. Its value is the address of the first element of the array. Thus, a pointer to an array may be declared and assigned as shown below.

Can an array be a pointer in C?

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4]. In the above example, p is a pointer to double, which means it can store the address of a variable of double type.


1 Answers

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.

like image 62
Cauterite Avatar answered Sep 22 '22 20:09

Cauterite