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

Sel*_*_va 5 c# c++ pinvoke marshalling

我从C#调用两个C++函数.虽然在大约100万次调用的迭代中这样做,但我看到了大约30%的开销.

C++函数:

EXTERN_C void STDAPICALLTYPE FunctionA(UINT_PTR mathId)
{
    ...
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

[DllImport("CPlusPlus.dll")]
    public static extern void FunctionA([In] IntPtr mathID);
Run Code Online (Sandbox Code Playgroud)

从以下功能调用:

 public static void HelpingFunction([In]UInt64 mathID)
    {
        FunctionA((IntPtr)mathID);
    }
Run Code Online (Sandbox Code Playgroud)

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

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

Sul*_*lNR 8

你可以尝试添加SuppressUnmanagedCodeSecurityAttribute.

允许托管代码在没有堆栈遍历的情况下调用非托管代码.

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

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

PInvoke每次调用的开销在10到30 x86之间.除了这个固定成本之外,编组还会产生额外的开销.在管理和非托管代码中具有相同表示的blittable类型之间没有编组成本.例如,在int和Int32之间进行转换没有成本.

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