简体   繁体   中英

AccessViolationException in PInvoke function call with double arrays and void pointers

I want to call two functions from a DLL with pure-C interface via PInvoke with the following signatures:

void *pj_init_plus(const char *srsName);
int pj_datum_transform(void *src, void *dst, long point_count, int point_offset,
                    double *x, double *y, double *z );

Pinvoke methods:

[DllImport("proj.dll", CallingConvention = CallingConvention.Cdecl, 
    EntryPoint = "pj_init_plus", CharSet = CharSet.Ansi)]
public static extern IntPtr PjInit(string srsName);

[DllImport("proj.dll", EntryPoint = "pj_transform", CallingConvention =
    CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int PjTransformation(IntPtr src, IntPtr dst,long pointCount,
    int pointOffset, double[] x, double[] y,double[] z);

In my C#-code i call the methods:

IntPtr pjSrc = PjInit("+proj=longlat +datum=WGS84 +no_defs");
IntPtr pjDst = PjInit("+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs");

double[] x = { 4489580.7, 4489580.7 };
double[] y = { 5320767.7, 5320767.7 };
double[] z = { 0.0, 0.0};

PjTransformation(pjSrc, pjDst, x.Length, 1, x, y, z);

The PjInit-call works fine and returns a valid pointer. But calling PjTransformation throws an AccessViolationException-Exception. I think there is a problem with the double arrays. In one post was mentioned, that a clr-array is already compatible with a native array and has not to be manually marshalled. I also tried it with the attribute [MarshalAs(UnmanagedType.LPArray)] for the double-arrays, but that didn't help. Or could the Exception come from the struct which is returned as a void pointers from the first function call. The problem is i don't know the type of the struct.

The dll functions are ok, i tried it with native c-code and it worked. Also the parameter pointOffset could not cause the exception.

Your P-invoke declaration looks good and valid. The only issue I can think of is that the AV exception is thrown from the native function itself rather than when the marshaling takes place.

I advise that you try to debug the code using a native debugger, you can than spot the exact line of code where the exception is thrown and diagnose if the problem occurs during marshalling or actual function execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM