1

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.

1
  • 1
    Have you tried testing your hypotheses by creating wrappers around the C methods? I.e. create a C method that returns void instead of the struct and p/invoke that. If that works, then the struct is the issue and you can debug that. If it still fails, create an overload that doesn't accept the double arrays and try again. Commented Oct 10, 2013 at 19:02

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.