extern __gshared const(char)* symbol fails

nkm1 t4nk074 at openmailbox.org
Fri Aug 31 18:01:05 UTC 2018


On Friday, 31 August 2018 at 06:20:09 UTC, James Blachly wrote:
> Hi all,
>
> I am linking to a C library which defines a symbol,
>
> const char seq_nt16_str[] = "=ACMGRSVTWYHKDBN";
>
> In the C sources, this is an array of 16 bytes (17 I guess, 
> because it is written as a string).
>
> In the C headers, it is listed as extern const char 
> seq_nt16_str[];
>
> When linking to this library from another C program, I am able 
> to treat seq_nt16_str as any other array, and being defined as 
> [] fundamentally it is a pointer.

No. This is a misconception. Fundamentally, it's an array.

>
> When linking to this library from D, I have declared it as:
>
> extern __gshared const(char)* seq_nt16_str;
>
> ***But this segfaults when I treat it like an array (e.g. by 
> accessing members by index).***
>
> Because I know the length, I can instead declare:
>
> extern __gshared const(char)[16] seq_nt16_str;
>
> My question is: Why can I not treat it opaquely and use it 
> declared as char* ? Does this have anything to do with it being 
> a global stored in the static data segment?

For the same reason you can't do it in C.

--- main.c ---
#include <stdio.h>

extern const char* array; /* then try array[] */

int main(void)
{
     printf("%.5s\n", array);
     return 0;
}

--- lib.c ---
const char array[] = "hello world";


# gcc -o main main.c lib.c
# ./main
Segmentation fault

You need to declare your extern array as array in D and also in 
C, so that the compiler would know what that is (an array, not a 
pointer). In many situations C compiler would silently convert an 
array into a pointer (when it already knows its dealing with 
array), but it won't convert a pointer into an array.


More information about the Digitalmars-d-learn mailing list