6

I am calling two C++ functions from C#. While doing that in a iteration for around 1 million call i am seeing a overhead of about 30%.

C++ function :

EXTERN_C void STDAPICALLTYPE FunctionA(UINT_PTR mathId) { ... ... } 

In my C# assembly dll as :

[DllImport("CPlusPlus.dll")] public static extern void FunctionA([In] IntPtr mathID); 

Called from function as below:

 public static void HelpingFunction([In]UInt64 mathID) { FunctionA((IntPtr)mathID); } 

This way of implementation is creating more overhead when the "HelpingFunction" is called more than a million times.

Can someone give me other ideas so that the overhead can be reduced? What are the other ways to call a C++ function from a C# assembly?

2
  • Very hard to know how you could improve this, because we cannot see the insides of FunctionA. Commented May 18, 2015 at 14:35
  • You might also consider writing a CLI wrapper around the loop, so your overhead is reduced from "millions" of calls to just a few. Commented May 18, 2015 at 15:01

1 Answer 1

8

You can try to add SuppressUnmanagedCodeSecurityAttribute.

Allows managed code to call into unmanaged code without a stack walk.

https://msdn.microsoft.com/en-us/library/system.security.suppressunmanagedcodesecurityattribute.aspx

But on p/invoke call always will be fixed cost overhead:

PInvoke has an overhead of between 10 and 30 x86 instructions per call. In addition to this fixed cost, marshaling creates additional overhead. There is no marshaling cost between blittable types that have the same representation in managed and unmanaged code. For example, there is no cost to translate between int and Int32.

https://msdn.microsoft.com/en-us/library/ms235282.aspx

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

2 Comments

do u mean adding [System.Security.SuppressUnmanagedCodeSecurity] above the function "HelpingFunction(..)" definition ?
no, above DllImport or like this [DllImport("CPlusPlus.dll"), System.Security.SuppressUnmanagedCodeSecurity]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.