D array to void* and back
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Aug 3 15:36:18 PDT 2015
On 8/3/15 5:23 PM, ref2401 wrote:
> Hello everyone,
>
> I pass a D array as void* into a function.
>
> When I'm trying to cast a void* parameter to a D array I get 'Access
> Violation' error.
> However if I define ArrayLike struct which looks like D array then
> casting will succeed.
> What should I do? Should I stick to ArrayLike wrapper and just live? :)
>
> struct ArrayLike(T) {
> this(T[] arr) {
> ptr = arr.ptr;
> length = arr.length;
> }
>
> T* ptr;
> size_t length;
In T[], length is stored first, then pointer. This is likely where you
are getting hung up. You didn't post your C code, so I don't know
exactly what you are expecting on the other side.
>
> T[] asArray() {
> return ptr[0 .. length];
> }
> }
>
> void funcLibC_Array(void* data) {
> int[] arr = *cast(int[]*)data;
> writeln("funcLibC_Array: ", arr);
> }
>
> void funcLibC_ArrayLike(void* data) {
> ArrayLike!int arrLike = *cast(ArrayLike!int*)data;
> writeln("funcLibC_ArrayLike: ", arrLike.asArray());
> }
>
> void main(string[] args) {
> int[] arr = [1, 2, 3];
> auto arrLike = ArrayLike!int(arr);
>
>
> funcLibC_ArrayLike(&arrLike);
> funcLibC_Array(arr.ptr); // 'Access Violation error' is thrown here.
This is wrong, arr.ptr is just the pointer to the DATA, not a pointer to
an array struct (which contains pointer and length). You want to do
funcLibC_Array(&arr);
Posting your C code (at least the part that reestablishes the type from
a void*) may give more clarity to what you are trying to do.
-Steve
More information about the Digitalmars-d-learn
mailing list