2014-03-25 51 views
0

我目前正在嘗試爲我的G19使用Logitech sdk。Logitech SDK C#使用

我可以找到關於這個主題的所有信息,從2012年開始,許多方法改變了名字,我決定嘗試做一個新的.NET包裝。

但是,我卡住了,沒有得到任何地方。

我第一次創建了一個庫項目。 這裏是庫代碼:

using System; 
using System.Runtime.InteropServices; 
using System.Text; 

namespace Logitech_LCD 
{ 


    /// <summary> 
    /// Class containing necessary informations and calls to the Logitech SDK 
    /// </summary> 
    public class NativeMethods 
    { 
     #region Enumerations 
     /// <summary> 
     /// LCD Types 
     /// </summary> 
     public enum LcdType 
     { 
      Mono = 1, 
      Color = 2, 
     } 

     /// <summary> 
     /// Screen buttons 
     /// </summary> 
     [Flags] 
     public enum Buttons 
     { 
      MonoButton0 = 0x1, 
      ManoButton1 = 0x2, 
      MonoButton2 = 0x4, 
      MonoButton3 = 0x8, 
      ColorLeft = 0x100, 
      ColorRight = 0x200, 
      ColorOK = 0x400, 
      ColorCancel = 0x800, 
      ColorUp = 0x1000, 
      ColorDown = 0x2000, 
      ColorMenu = 0x4000, 
     } 
     #endregion 

     #region Dll Mapping 
     [DllImport("LogitechLcd.dll", CallingConvention = CallingConvention.Cdecl))] 
     public static extern bool LogiLcdInit(String friendlyName, LcdType lcdType); 

     [DllImport("LogitechLcd.dll", CallingConvention = CallingConvention.Cdecl))] 
     public static extern bool LogiLcdIsConnected(LcdType lcdType); 
     #endregion 
    } 
} 

然後,在一個虛擬的應用程序,我試着撥打LogiLcdInit

Console.WriteLine(Logitech_LCD.NativeMethods.LogiLcdIsConnected(Logitech_LCD.NativeMethods.LcdType.Color)); 
Console.WriteLine(Logitech_LCD.NativeMethods.LogiLcdInit("test", Logitech_LCD.NativeMethods.LcdType.Color)); 
Console.WriteLine(Logitech_LCD.NativeMethods.LogiLcdIsConnected(Logitech_LCD.NativeMethods.LcdType.Color)); 

現在的問題是:對於每行的內容,我得到一個PInvokeStackImbalance異常。沒有更多的細節,除了方法名稱。

這裏是將Logitech SDK鏈路參考

編輯:改變了代碼以反映碼的變化,由於該答案

編輯2

這裏是.NET包裝我對你的答案表示感謝:https://github.com/sidewinder94/Logitech-LCD

只是把它放在這裏用作ar eference。

+0

呃。我想檢查P/Invoke的簽名是否與實際的函數匹配(如果它們不同,則會出現堆棧不平衡)。但是你提供的SDK缺少頭文件。 –

+0

更新了鏈接,更正了一個可用,我的壞 – Sidewinder94

回答

2

這是因爲DllImport attribute defaults to the stdcall calling convention,但Logitech SDK使用cdecl調用約定。

此外,C++中的bool僅佔用1個字節,當C#運行時試圖解組4個字節時。您必須告訴運行時將bool編組爲1個字節,而不是使用另一個屬性的4個字節。

所以你的最終進口放棄尋找這樣的:

[DllImport("LogitechLcd.dll", CallingConvention=CallingConvention.Cdecl)] 
[return:MarshalAs(UnmanagedType.I1)] 
public static extern bool LogiLcdInit(String friendlyName, LcdType lcdType); 

[DllImport("LogitechLcd.dll", CallingConvention=CallingConvention.Cdecl)] 
[return:MarshalAs(UnmanagedType.I1)] 
public static extern bool LogiLcdIsConnected(LcdType lcdType); 
+0

偉大的事情,我沒有例外了,現在的問題是:返回值始終爲真 對於LogiLcdIsConnected方法,如果在初始化之前調用,它應該返回false if我正確理解 – Sidewinder94

+0

另外:你是如何確定命名約定的? – Sidewinder94

+0

這是一個*調用*約定,並且C#中只有3個可用:)另外,在得到答案之後儘量不要改變問題,這很容易混淆,或者非常清楚你正在做一個回答後編輯! –