On Sunday, 22 April 2012 at 23:01:26 UTC, jerro wrote:
On Sunday, 22 April 2012 at 22:17:11 UTC, Stephen Jones wrote:
Thanks for the replies. I am still uncertain about something. The documentation distinguishes between dynamic slices (int[5] a = new int[5]) which are managed by the runtime, and stack allocated arrays (int[5] b). The problem I have is this. I want to be loading vertex positions and tex-coords of data exported from Blender into openGL vertex buffers. Basically the float data needs to be extracted from a file and passed up to the graphic card's memory but to do so it needs to transit through the CPU memory. Ideally I want to: a) load the data from the file into an array built upon the stack and owned by a function b) generate the vbo id and send the data off to the graphics card
   c) pass the id back into a class held in managed memory
   d) quit the function thus releasing the array on the stack

My confusion is, if the syntax for both stack based and managed memory arrays is the same (&v[0] or &v.ptr) then both must be objects. I guess the difference is that stack based are of constant length, whereas slices are dynamic because they are managed by the runtime.

Dynamic arrays in D are represented with a struct containing
a pointer to the start of data and a length. Static arrays are
represented in the same way as they are in C - just the data is
saved, the length is known at compile time and the pointer to data
is computed from the stack frame pointer (or a pointer to
struct if the static array is contained within a struct) and the
offset which is also know at compile time, the same way the pointers to primitive types are computed. For example the following D program:

import std.stdio;

auto vp(T)(T* a){ return cast(void*) a; }

struct S
{
        int[8] a;
        int[8] b;
        int[]  c;
        int[8] d;
}

void main()
{
        S s;
        writeln( vp(&s.a) - vp(&s.a[0]));
        writeln(vp(&s.b) - vp(&s.a));
        writeln(vp(&s.c) - vp(&s.b));
        writeln(vp(&s.d) - vp(&s.c));
}

and the following C program:

#include <stdio.h>

#define vp(a) (void*)(a)

typedef struct
{
        int* ptr;
        size_t length;
} IntArray;

typedef struct
{
        int a[8];
        int b[8];
        IntArray  c;
        int d[8];
} S;

int main()
{
        S s;
        printf("%d\n", vp(&s.a) - vp(&s.a[0]));
        printf("%d\n", vp(&s.b) - vp(&s.a));
        printf("%d\n", vp(&s.c) - vp(&s.b));
        printf("%d\n", vp(&s.d) - vp(&s.c));
        return 0;
}

both print

0
32
32
16

Just to clarify, .ptr and .length aren't really fields, they
are properties. Dynamic arrays are actually represented as
structs containing a pointer and a length, but static arrays
are not. The fact that they have .ptr and .length properties
does not imply they are represented as structs with .ptr and
.length fields.

Reply via email to