Skip to content

Benchmarks for #115746 (davidwrighton) #424

@EgorBot

Description

@EgorBot

Processing dotnet/runtime#115746 (comment) command:

Command

-arm

using System;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

namespace PInvokeBenchmark
{
    public class PInvokeBenchmarks
    {
        // Define a delegate type for our managed function
        private delegate int ManagedDelegate(bool value);
        
        // Define a matching function pointer type for unmanaged calls
        private unsafe delegate int UnmanagedDelegate(bool value);
        
        // The managed implementation
        private static int ManagedImplementation(bool value)
        {
            return value ? 42 : 0;
        }
        
        // Our instance of the delegate
        private readonly ManagedDelegate _managedDelegate;
        
        // Marshaled function pointer
        private readonly unsafe delegate* unmanaged<bool, int> _nativeFunctionPointer;
        
        // Delegate wrapping the marshaled function pointer
        private readonly unsafe delegate* unmanaged<bool, int> _unmanagedDelegate;

        // P/Invoke declaration for the native method
        [DllImport(@"C:\temp\pinvokeBench\NativeDll\NativeDll.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int Method(bool value);


        public unsafe PInvokeBenchmarks()
        {
            // Create the managed delegate
            _managedDelegate = ManagedImplementation;

            // Marshal it to a native function pointer
            _nativeFunctionPointer = (delegate* unmanaged<bool, int>)Marshal.GetFunctionPointerForDelegate(_managedDelegate);

        }

        [Benchmark]
        public unsafe int MarshaledDelegateCall()
        {
            return _nativeFunctionPointer(true);
        }
    }
}

(EgorBot will reply in this issue)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions