开销 - 从 C# 调用 C++ 函数

Overhead - Calling C++ function from C#

我正在从 C# 调用两个 C++ 函数。在大约 100 万次调用的迭代中执行此操作时,我发现开销约为 30%。

C++ 函数:

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

在我的 C# 程序集 dll 中为:

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

从函数调用如下:

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

当 "HelpingFunction" 被调用超过一百万次时,这种实现方式会产生更多开销。

有人可以给我其他想法以减少开销吗?从 C# 程序集调用 C++ 函数的其他方法是什么?

您可以尝试添加SuppressUnmanagedCodeSecurityAttribute

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

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

但是在 p/invoke 上调用总是会产生固定成本开销:

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