Binding to C - Arrays and Access Violation

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 2 16:37:25 PST 2016


On Tuesday, 2 February 2016 at 22:56:28 UTC, jmh530 wrote:

>
> 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)

>
> 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...

The parameter to the C function should be declared as extern(C), 
and so should your function implementation.

extern(C) alias FuncPtr = double function(uint, const(double)*, 
double*, void*);
extern(C) void takeFuncPtr(FuncPtr);

extern(C) double myfunc(uint n, const(double)* x, double* grad, 
void* my_func_data) {
...
}

If you haven't done that, then this is quite possibly the root of 
your problem.




More information about the Digitalmars-d-learn mailing list