C-binding external array.
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Aug 9 12:16:46 PDT 2016
On 08/09/2016 11:46 AM, ciechowoj wrote:
> On Tuesday, 9 August 2016 at 15:41:08 UTC, Steven Schveighoffer wrote:
>> @property int* tabp() { return tab.ptr; }
>>
>> tabp[elem];
>
> This is nice. The best would be to have it with the same name as
> original symbol, but I can't imagine how it could be done.
Well, C's array symbol is used as a pointer to the first element and D
allows array indexing for pointers as well.
Here is the C code:
// c.c
#include "stdio.h"
int tab[64];
int *get() {
return tab; // or &tab[0]
}
void info() {
printf("%p\n", tab);
}
void write_at(int i, int value) {
tab[i] = value;
}
int read_at(int i) {
return tab[i];
}
The D code uses the array as a pointer and then makes a slice at the
very end:
// d.d
import std.stdio;
extern (C) {
int *get();
void info();
void write_at(int i, int value);
int read_at(int i);
}
void main() {
int *tab = get();
info();
writefln("0x%s", tab);
// make sure we can see what C writes
write_at(7, 77);
assert(tab[7] == 77);
// make sure C can read what we write
tab[42] = 42;
assert(read_at(42) == 42);
// If you know the size, use as a D array
int[] tab_D = tab[0..64];
writeln(tab_D);
}
Ali
More information about the Digitalmars-d-learn
mailing list