Passing a C# callback function through Interop/pinvoke

前端 未结 2 1561
醉梦人生
醉梦人生 2020-12-01 08:16

I am writing a C# application which uses Interop services to access functions in a native C++ DLL. I am already using about 10 different functions which are working.

<
2条回答
  •  执念已碎
    2020-12-01 08:33

    This works for me:

    Calc.h (Calc.dll, C++):

    extern "C" __declspec(dllexport) double Calc(double x, double y, double __stdcall p(double, double));
    

    Calc.cpp (Calc.dll, C++):

    #include "calc.h"
    
    __declspec(dllimport) double Calc(double x, double y, double __stdcall p(double, double))
    {
        double s = p(x*x, y*y);
        return x * y + s;
    }
    

    Program.cs (Sample.exe, C#):

    class Program
    {
        delegate double MyCallback(double x, double y);
        [DllImport("Calc.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern double Calc(double x, double y, [MarshalAs(UnmanagedType.FunctionPtr)]MyCallback func);
    
        static void Main(string[] args)
        {
            double z = Calc(1, 2, (x, y) => 45);
        }
    }
    

提交回复
热议问题