Thread overview
Passing string array to C
September 10
Hi,

I have this coding. Function `sample` will later be called from C
and should provide access to a string array.

I tried to read the string values after the function call
and I can access the first string, but for the second string,
there is an access violation.

Why does it crash?

Kind regards
André

```
import std;

void main()
{
	size_t* i;
	const(wchar)* r;
	sample(&r, &i);

        // Try to read the 2 string values
	const(wchar) ** r2;
	r2 = &r;
	auto arr = r2[0..*i];
	writeln(to!string(arr[0])); // Works
	writeln(to!string(arr[1])); // Fails
}

extern(C) export void sample(const(wchar)** r, size_t** c)
{
	string[] arr = ["fooä", "bar"];
	auto z = new const(wchar)*[arr.length];
	foreach(i, ref p; z)
	{
		p = toUTF16z(arr[i]);
	}
	
        *r = z[0];
	
	*c = new size_t();
	**c = arr.length;
}
```

September 10
On Thursday, 10 September 2020 at 14:31:41 UTC, Andre Pany wrote:
> Why does it crash?

You messed up the pointers.

A string is one star.

An array of strings is two stars.

A pointer to an array of strings is /three/ stars.

---
import std;

void main()
{
        size_t* i; // this need not be a pointer either btw
        const(wchar)** r; // array of strings
        sample(&r, &i); // pass pointer to array of strings

        // Try to read the 2 string values
        auto arr = r[0..*i]; // slice array of strings
        writeln(to!string(arr[0])); // Works
        writeln(to!string(arr[1])); // all good
}

// taking a pointer to an array of strings so 3 stars
extern(C) export void sample(const(wchar)*** r, size_t** c)
{
        string[] arr = ["foo¤", "bar"];
        auto z = new const(wchar)*[arr.length];
        foreach(i, ref p; z)
        {
                p = toUTF16z(arr[i]);
        }

        // previously you were sending the first string
        // but not the pointer to the array
        // so then when you index above, arr[1] is bad math
        *r = &z[0];

        *c = new size_t();
        **c = arr.length;
}
---
September 10
On Thursday, 10 September 2020 at 15:41:17 UTC, Adam D. Ruppe wrote:
> On Thursday, 10 September 2020 at 14:31:41 UTC, Andre Pany wrote:
>> [...]
>
> You messed up the pointers.
>
> [...]

Fantastic, thank you so much Adam.

Kind regards
André