D array to void* and back

ref2401 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 3 14:23:38 PDT 2015


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;

	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.
}



More information about the Digitalmars-d-learn mailing list