Passing a C# callback function through Interop/pinvoke

早过忘川 提交于 2019-11-27 07:50:51

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);
    }
}

Can you try changing the Func delegate to

    public delegate void Func([In, MarshalAs(UnmanagedType.LPStr)] string arg1, [In, MarshalAs(UnmanagedType.LPStr)] string arg2);

And the SetFunc method to

[DllImport("lib", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
public static extern int SetFunc(Func lpfn);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!