Wout

Hi,

I've done some performance measurement on different styles of P-Invoke signatures. The original signature takes 3 doubles as an argument. I have experimented by adding an overload which takes a struct as an argument, where the struct contains 3 doubles. Somehow this method is about a factor 15 slower!

Is there a bug in the marshaling As far as I can find information about it, a struct only containing blittables, should itself also be blittable (see http://msdn2.microsoft.com/en-us/library/75dwhxf7.aspx). So therefore I would have expected the exact same performance.

The struct is defined as follows:

[StructLayout(LayoutKind.Sequential)]
public struct Point {
public double x, y, z;
}

Wout



Re: Common Language Runtime P-Invoke struct marshaling performance issue.

nobugz

The marshaler needs to allocate unmanaged memory, figure out member alignment, copy the struct, call the unmanaged function, copy back any changes, then free the memory. That's expensive. Three double arguments can just be passed on the stack.





Re: Common Language Runtime P-Invoke struct marshaling performance issue.

Wout

Thanks for the answer... I would have hoped that the compiler realized the struct was blittable and didn't do anything, but alas.

Anyway, I'm looking for a solution. Would moving to C++/CLI and using IJW be a proper way out Oh, note that I'm building a managed wrapper for some native code, so I'll be using it from C# mainly. So going the IJW way would mean having some static methods forwarding the calls using IJW.

Alternative I could write a static C# method doing the call, but doing the P-Invoke overload seemed more elegant (except for the compiler screwing it up again).

Wout





Re: Common Language Runtime P-Invoke struct marshaling performance issue.

nobugz

It's not the compiler, it is the marshaler that makes this slow. The StructLayout attribute makes it un-blittable. You can't leave it off. C++ Interop might help, you could put the native struct on the stack rather than in the unmanaged heap. If you want an answer without trying, you better post at the C++ General forum.