如何将参数发送到DLL

时间:2018-01-12 18:50:54

标签: c# dll pinvoke

我的C#WPF项目中有一个DLL文件,我想访问一个DLL文件。这有效,但我不知道如何添加参数。

参考:

enter image description here

我目前的代码:

namespace Universal_RGB_Sync
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MLAPI_Initialize_();
        }

        private void btnColorRed_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Return code: " + SetLedColor("1", Convert.ToUInt32(1), Convert.ToUInt32(255), Convert.ToUInt32(0), Convert.ToUInt32(0)));
        }

        public const string sMysticLightDll = "C:\\GitHub\\UniversalRGB\\Universal RGB Sync\\MysticLight_SDK.dll";

        [DllImport(sMysticLightDll, CharSet = CharSet.Unicode, EntryPoint = "MLAPI_Initialize")]
        public static extern int MLAPI_Initialize_();

        [DllImport(sMysticLightDll, CharSet = CharSet.Unicode, EntryPoint = "MLAPI_SetLedColor")]
        public static extern Int16 MLAPI_SetLedColor_(IntPtr bstr, UInt32 index, UInt32 R, UInt32 G, UInt32 B);

        Int16 SetLedColor(string text, UInt32 index, UInt32 R, UInt32 G, UInt32 B)
        {
            IntPtr textPtr = Marshal.StringToHGlobalUni(text);
            Int16 status = MLAPI_SetLedColor_(textPtr, index, R, G, B);
            return status;
        }
    }
}

我想在执行MLAPI_SetLedColor_时发送值。我怎么能这样做?

更新:

我现在有了上面的代码,但在按下按钮后,我收到了这个错误:

  

托管调试助手' PInvokeStackImbalance' :'打电话给   PInvoke功能'通用RGB   同步Universal_RGB_Sync.MainWindow :: MLAPI_SetLedColor _&#39!;不平衡   堆栈。这很可能是因为托管PInvoke签名   不匹配非托管目标签名。检查是否正在通话   PInvoke签名的约定和参数与目标匹配   非托管签名。'

2 个答案:

答案 0 :(得分:1)

这是代码。在think中,initialize应返回Int16而不是Int(32位)。为任何对可变大小感兴趣的人发现了一篇很棒的Wiki文章:https://en.wikipedia.org/wiki/Word_(computer_architecture)

    class MysticLight
    {
        public const string sMysticLightDll = "C:\\GitHub\\UniversalRGB\\Universal RGB Sync\\MysticLight_SDK.dll";

        [DllImport(sMysticLightDll, CharSet = CharSet.Unicode, EntryPoint = "MLAPI_Initialize")]
        public static extern int MLAPI_Initialize_();

        [DllImport(sMysticLightDll, CharSet = CharSet.Unicode, EntryPoint = "MLAPI_SetLedColor")]
        public static extern Int MLAPI_SetLedColor_(IntPtr bstr, Uint32 index, UInt32 R, UInt32 G, UInt32 B);

        Int16 SetLedColor(string text,UInt32 index, UInt32 R, UInt32 G, UInt32 B)
        {
            IntPtr textPtr = Marshal.StringToHGlobalUni(text);
            Int status = MLAPI_SetLedColor_(textPtr, index, R, G, B);
            return status;
        }
    }

答案 1 :(得分:-1)

您需要更改[DllImport] ed声明以包含要发送的参数。声明应该匹配(可能与编组属性)函数期望接收的任何内容。