Array pointer from C to D

I use D and interact with some C libraries. As a result, I have to convert D arrays to pointers for C (for example, short *). Currently, I just throw them like this:

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

It is not safe? I have tried:

 myCFunction(&dArray); 

But this makes the function int [] * instead of int *. I see that in C ++ some people take the first element as follows:

 myCFunction(&dArray[0]); 

But will this pointer only point to the first element? I am new to pointers and links since I came from the Java world.

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

+5
source share
1 answer

In D, the array is actually (conceptually):

 struct { size_t length; void* ptr; }; 

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

But will this pointer only point to the first element

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

Another point: usually, if the C function wants an array pointer, it also has an argument for the length of the array. In most cases, you can give it dArray.length , but sometimes it actually asks for the size in bytes, not the number of elements.

+11
source

All Articles