本文介绍了通过 Interop/pinvoke 传递 C# 回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 C# 应用程序,它使用互操作服务访问本机 C++ DLL 中的函数.我已经在使用大约 10 个不同的功能了.

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.

现在我不确定如何处理将回调作为参数传递以便 DLL 可以调用我的代码.

Now I am not sure how to handle passing a callback as a parameter so that the DLL can call my code.

这里是DLL的函数原型:

Here is the function prototype of the DLL:

typedef void (WINAPI * lpfnFunc)(const char *arg1, const char *arg2)

以及允许我传递上述类型的函数:

And the function that allows me to pass the above type:

int WINAPI SetFunc(lpfnFunc f)

这是我的委托和函数定义的 C# 代码:

Here is my C# code for the delegate and function definitions:

public delegate void Func(string arg1, string arg2);

public static void MyFunc(string arg1, string arg2)

这是我的 SetFunc Interop 函数的 C# 代码:

Here is my C# code for the SetFunc Interop function:

[DllImport("lib.dll", CharSet = CharSet.Ansi)]
public static extern int SetFunc(Func lpfn);

最后是我调用 SetFunc 函数并将其传递给我的回调的代码:

And finally here is the code where I call the SetFunc function and pass it my callback:

SetFunc(new Func(MyFunc));

不幸的是,我的函数没有在应该调用的时候被调用.SetFunc 函数的返回值返回的是 Success 的错误代码,所以它要么没有调用我的函数,要么因为我的代码错误而无法工作.

Unfortunately my function is not being called when it should be. The return value of the SetFunc function is returning the error code for a Success, so either it's not calling my function or it's not working because my code is wrong.

推荐答案

这对我有用:

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

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++):

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#):

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

这篇关于通过 Interop/pinvoke 传递 C# 回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:18