如何在 C# 中通过引用创建一个 dll 函数,从 MQL4 接受值并返回它?

How to create a dll function by reference in C# accepting values from MQL4 and returning it?

这里是原函数:

    public  static  void GetEvent ( int event_n, ref  string el_name, ref  int id,   ref  long lparam, ref  double dparam, ref  string sparam)
    {         
            GuiEvent e = m_global_events [event_n];
            el_name = e.el_name;
            id = ( int ) e.id;
            lparam = e.lparam;
            dparam = e.dparam;
            sparam = e.sparam;

    }

这是我尝试过的:

public  static  void GetEvent ([MarshalAs (UnmanagedType.I4)] int event_n, [MarshalAs (UnmanagedType.LPTStr)] ref  string   el_name, [MarshalAs (UnmanagedType.I4)] ref  int id, [MarshalAs (UnmanagedType.I8)] ref  long lparam, [MarshalAs (UnmanagedType.R8)] ref  double dparam, [MarshalAs (UnmanagedType.LPTStr)] ref  string sparam)
        {
            GuiEvent e = m_global_events [event_n];
            el_name = e.el_name;
            Console.WriteLine (e.el_name);
            id = ( int ) e.id;
            lparam = e.lparam;
            dparam = e.dparam;
            sparam = e.sparam;
        }

我收到一个错误:

Access violation  

请让我知道我可以做些什么来使其与 MQL4 一起工作。

Dll 访问方式如下:

#import    "my.dll"  
void GetEvent ( int index, string element_name, int elemnet_id, long element_lparam, double element_dparam, string element_sparam);
#import

我想我可以解决你的问题。
这是:
首先,让我们修复您的 C# Dll 函数:
它必须是这样的:

[DllExport("GetEvent", CallingConvention = CallingConvention.StdCall)]
public static void GetEvent([MarshalAs(UnmanagedType.I4)] int event_n, [In, Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder el_name, [In, Out, MarshalAs(UnmanagedType.I4)] ref int el_id,
    [In, Out, MarshalAs(UnmanagedType.I8)]ref long lparam, [In, Out, MarshalAs(UnmanagedType.R8)]ref double dparam, [In, Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder sparam)
{
    GuiEvent e = m_global_events[event_n];
    _ = el_name.Replace("-1", e.el_name);
    el_id = (int)e.id;
    lparam = e.lparam;
    dparam = e.dparam;
    _ = sparam.Replace("-1", e.sparam);
}

现在修复 C# 函数后,让我们改进您的 MQL4:

#import    "my.dll"  
void GetEvent ( int index, string &element_name, int &elemnet_id, long &element_lparam, double &element_dparam, string &element_sparam);
#import

现在要访问这些值,您必须使用如下方式调用函数:

void OnInit()
{
string name="-1", sparam="-1";
      int id;
      long lparam;
      double dparam;
      GetEvent(0, name, id, lparam, dparam, sparam);
      PrintFormat("name: %s, id: %d, lparam: %ld, dparam: %lf, sparam: %s",name, id, lparam, dparam, sparam);
}

希望对您有所帮助。以下是一些对您将来有帮助的参考资料: 参考:https://www.mql5.com/en/articles/249, https://www.mql5.com/en/forum/150219, https://www.mql5.com/en/forum/149586