JustOnePixel
JustOnePixel

Reputation: 699

Is there a performance advantage in using unsafe P/Invoke calls over normal p/Invoke calls?

I'm looking to use P/Invoke to allow my C# assembly to interop with a native C library; this needs to be cross-platform (i.e. Mono), so a mixed-mode assembly cannot be used. I'm wondering if there is any performance advantage to using unsafe P/invoke calls, and handling all the conversions to pointers in an unsafe method, versus making the typical "safe" P/Invoke call. Thanks in advance!

CLARIFICATION: I am not looking to use a managed C++ wrapper, as is discussed here. I just want to know if there are performance differences between:

extern static void native_call_here(IntPtr parameter1, String parameter2)

and

extern static void native_call_here(int* parameter1, char* parameter2)

Upvotes: 4

Views: 1157

Answers (1)

Dan Bryant
Dan Bryant

Reputation: 27515

There is going to be Marshaling at some point. In the former case, the Marshaling occurs as soon as you make the PInvoke method call. In the latter case, since you're calling from unsafe code, you have control over when/how the Marshaling occurs. This could offer a benefit if you're doing multiple operations with unmanaged memory in your unsafe code, but if it's just passing the data through, all you've done is shifted where the Marshaling occurs. If anything, I would expect the PInvoke to be faster in this case, but, as always, profile it if it matters.

Upvotes: 4

Related Questions