首页 > 解决方案 > 如何在 C# 中使用具有多个参数的委托函数

问题描述

我有委托功能,即:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void AddMultiInformation([MarshalAs(UnmanagedType.LPStr)] string str, 
                                  [MarshalAs(UnmanagedType.LPStr)] string str2,
                                  [MarshalAs(UnmanagedType.LPStr)] string str3);

我在 C DllImported 函数的回调中使用此委托函数,如下所示。

[DllImport("CarsDLL.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern int GetCarsInformations(AddMultiInformation carsData);

请问我可以使用哪种类型的参数来正确调用 GetCarsInformations 函数?

class Program
{
    // Constructor
    protected Program()
    {
    }

    // Main
    [STAThread]
    public static void Main()
    {
        //GetCarsInformations();
        Application.Exit();
    }
}

标签: c#

解决方案


匹配您代表的签名

public delegate void AddMultiInformation([MarshalAs(UnmanagedType.LPStr)] string str, 
                                         [MarshalAs(UnmanagedType.LPStr)] string str2,
                                         [MarshalAs(UnmanagedType.LPStr)] string str3);

你需要一个方法

  • 退货void
  • 恰好有三个参数,它们都是string.

所以,像

public void MethodThatAddsMultiInformation(string str, string str2, string str3)
{
    // put some logic in here
}

然后,您可以通过为其AddMultiInformation分配对方法的引用来创建委托的实例MethodThatAddsMultiInformation

AddMultiInformation addMultiInformation = MethodThatAddsMultiInformation;

然后GetCarsInformations用委托的实例调用:

var information = GetCarsInformations(addMultiInformation);

推荐阅读