Binding to C - Arrays and Access Violation
biozic via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 2 16:28:24 PST 2016
On Tuesday, 2 February 2016 at 22:56:28 UTC, jmh530 wrote:
> I'm working on generating a binding to a C library. I've got
> the .h file converted and can call some parts of the library
> with no errors. However, I have reached a stumbling block in a
> critical part.
>
> The library requires passing function pointers to various
> functions in the library. When I try to run these functions, I
> get an Access Violation error. I enabled additional DMD
> warnings, which helped pinpoint the issue.
>
> My D code calls a C function. One of the parameters to the C
> function is a function pointer to a D function. This D function
> (below) is one that I copied from the C library's tutorial. I
> only slightly changed the signature. This function is
> eventually called in other functions in the C library.
>
> double myfunc(uint n, const double* x, double* grad, void*
> my_func_data)
> {
> if (grad)
> {
> grad[0] = 0.0;
> grad[1] = 0.5 / sqrt(x[1]);
> }
> return sqrt(x[1]);
> }
>
> The line (though likely the next will too) that causes a
> problem is
>
> grad[0] = 0.0;
>
> Thus, as it is an Access Violation, I'm guessing the issue is
> with accessing elements of arrays in the D function from the C
> function. I don't know. When I try to call the D function in D,
> it works, but I have to refer to x and grad as x.ptr and
> grad.ptr.
>
> I'm not sure how to go about fixing this...
Is grad allocated in the D code? If so, it could have been
collected because the GC lost track of its use when passing to
and from the C code. Or is grad owned by the C code? If so,
either there is a bug in the library or it's misused, because its
memory has been freed/has never been allocated/has gone out of
scope.
More information about the Digitalmars-d-learn
mailing list