August 10, 2016 Re: C-binding external array. | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On Tuesday, 9 August 2016 at 19:16:42 UTC, Steven Schveighoffer wrote:
>
> D has an answer:
>
> pragma(mangle, "tab")
> extern extern(C) int[1] _ctab;
>
> @property int* tab() { return _ctab.ptr; }
>
> I still don't recommend doing this, for previously stated reasons.
>
This is really interesting :).
|
August 10, 2016 Re: C-binding external array. | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On Tuesday, 9 August 2016 at 19:16:46 UTC, Ali Çehreli wrote:
> 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);
> }
>
> [...]
>
The problem is, I do not have a control over the C source code.
|
August 10, 2016 Re: C-binding external array. | ||||
---|---|---|---|---|
| ||||
Posted in reply to ciechowoj | On 08/10/2016 02:05 AM, ciechowoj wrote:
> On Tuesday, 9 August 2016 at 19:16:42 UTC, Steven Schveighoffer wrote:
>>
>> D has an answer:
>>
>> pragma(mangle, "tab")
>> extern extern(C) int[1] _ctab;
>>
>> @property int* tab() { return _ctab.ptr; }
>>
>> I still don't recommend doing this, for previously stated reasons.
>>
>
> This is really interesting :).
>
Better with some mixin magic:
mixin template CArray(string symbol, T) {
pragma(mangle, symbol) extern extern(C) __gshared
mixin ("T[0] _c" ~ symbol ~ ";");
@property
mixin ("T* " ~ symbol ~ "() { return _c" ~ symbol ~ ".ptr; }");
}
mixin CArray!("tab", int);
tab[42] = 42;
Ali
|
August 10, 2016 Re: C-binding external array. | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On Wednesday, 10 August 2016 at 15:07:52 UTC, Ali Çehreli wrote:
> On 08/10/2016 02:05 AM, ciechowoj wrote:
> Better with some mixin magic:
>
> mixin template CArray(string symbol, T) {
> pragma(mangle, symbol) extern extern(C) __gshared
> mixin ("T[0] _c" ~ symbol ~ ";");
>
> @property
> mixin ("T* " ~ symbol ~ "() { return _c" ~ symbol ~ ".ptr; }");
> }
>
> mixin CArray!("tab", int);
>
> tab[42] = 42;
>
This is very tempting to use. The only thing that stops me from doing that is I am unsure if the 'property' tab behaves in all contexts the same way the standard array behaves.
|
Copyright © 1999-2021 by the D Language Foundation