c# - 通过 Interop/pinvoke 传递 C# 回调函数

标签 c# function interop callback pinvoke

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

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

这是DLL的函数原型(prototype):

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

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

int WINAPI SetFunc(lpfnFunc f)

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

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

public static void MyFunc(string arg1, string arg2)

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

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

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

SetFunc(new Func(MyFunc));

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

最佳答案

这对我有用:

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(示例.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);
    }
}

关于c# - 通过 Interop/pinvoke 传递 C# 回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9056048/

相关文章:

php 函数不更新 mysql 数据库

c# - ASP.NET - 当前上下文中不存在名称 'Context'

c# - 异步编码-等待所有返回-性能

c# - 创建实例时绝对奇怪的行为

javascript - 如何使用扩展运算符向对象添加属性而不是覆盖它?

c++ - 如何调用下面定义的函数?

c# - 查找在 FileSystemWatcher 中触发 Changed 事件时发生的更改

c# - 在 C# 中使用 Scripting.Dictionary

c++ - 使用 p/invoke 将字符串数组从 C# 编码到 C 代码

javascript - 如何尝试最新的 JS 互操作? https ://github. com/dart-lang/js-interop