C-binding external array.

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 9 08:41:08 PDT 2016


On 8/9/16 10:09 AM, ciechowoj wrote:
> On Tuesday, 9 August 2016 at 14:01:17 UTC, Steven Schveighoffer wrote:
>>
>> I think this should work:
>>
>> extern extern(C) int[1] tab;
>>
>> Then if you want to access the elements, use the tab.ptr[elem]
>>
>> If it's a global variable, tack on __gshared.
>>
>
> I've already tried this and works (64-bit at least on linux). But is it
> portable?

Yes. D is designed to interface with C in certain ways, and this should 
be portable.

> No other way that allow to access the `tab` directly (without ..ptr
> proxy) ?

Well, you can via properties:

@property int* tabp() { return tab.ptr; }

tabp[elem];

Essentially, tab is a symbol that points at some undetermined number of 
elements. Since it's undetermined, D doesn't allow safe easy access.

If you did int *tab, then it would think the symbol points at a pointer.

tab.ptr is a shortcut to &tab[0].

You could potentially do int tab, and then use (&tab)[elem].

Or if you know the number of elements, you can just declare them.

If it were me, I'd access it via tab.ptr, because it *is* an unsafe 
operation and I'd want to highlight that for future readers.

If something defines tab's length, I'd highly recommend wrapping the two:

extern(C) int tabLength(); // mythical mechanism or no?

@property int[] dtab { return tab.ptr[0 .. tabLength]; }

-Steve


More information about the Digitalmars-d-learn mailing list