Overhead - Calling C++ function from C#
Asked Answered
S

1

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?

Stewart answered 18/5, 2015 at 14:33 Comment(2)
Very hard to know how you could improve this, because we cannot see the insides of FunctionA.Fruiter
You might also consider writing a CLI wrapper around the loop, so your overhead is reduced from "millions" of calls to just a few.Dannadannel
Y
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

Yesman answered 18/5, 2015 at 14:43 Comment(2)
do u mean adding [System.Security.SuppressUnmanagedCodeSecurity] above the function "HelpingFunction(..)" definition ?Stewart
no, above DllImport or like this [DllImport("CPlusPlus.dll"), System.Security.SuppressUnmanagedCodeSecurity]Yesman

© 2022 - 2024 — McMap. All rights reserved.