Passing string array to C
Adam D. Ruppe
destructionator at gmail.com
Thu Sep 10 15:41:17 UTC 2020
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;
}
---
More information about the Digitalmars-d-learn
mailing list