2009-11-18 54 views
1

我具有.dll用C++編寫像這樣定義的函數:PInvoke的與「陌生」功能

EDK_API int EE_CognitivSetCurrentLevel (unsigned int userId, 
    EE_CognitivLevel_t level, 
    EE_CognitivAction_t level1Action, 
    EE_CognitivAction_t level2Action, 
    EE_CognitivAction_t level3Action, 
    EE_CognitivAction_t level4Action 
)  

Set the current Cognitiv level and corresponding action types. 


Parameters: 
userId - user ID 
level - current level (min: 1, max: 4) 
level1Action - action type in level 1 
level2Action - action type in level 2 
level3Action - action type in level 3 
level4Action - action type in level 4 

此功能的使用,因爲你可以看到上面:如果電平= 1,這是會這樣調用:

EE_CognitivSetCurrentLevel(userId,1,level1Action); 

如果級別= 2,則:

EE_CognitivSetCurrentLevel(userId,2,level1Action,level2Action); 

等等...

如何在C#中調用此函數?

非常感謝!

+0

C++'EE_CognitivSetCurrentLevel()'函數是使用默認參數編寫的,還是它是一個'__cdecl'函數,它可以接受可變數量的參數?正確的做法會因此而有所不同。 – 2009-11-18 06:10:35

+0

不幸的是,我沒有dll的原始源代碼。我怎麼知道它是使用默認參數編寫的,還是它是* _cdecl *函數? – Vimvq1987 2009-11-19 07:48:56

+0

如果默認值不使用相同的約定,則會得到錯誤的參數。如果你想明確地設置它,在我的答案中添加這個DllImport參數:CallingConvention = CallingConvention.Cdecl。如果需要,請查看http://msdn.microsoft.com/zh-CN/library/system.runtime.interopservices.callingconvention.aspx以獲取其他選項。 – Gonzalo 2009-11-20 03:30:55

回答

3

假設EE_CognitivLevel_tEE_CognitivAction_t是整數:

[DllImport ("yourdll", EntryPoint ("EE_CognitivSetCurrentLevel")] 
extern static int EE_CognitivSetCurrentLevel1 (int level, int level1); 

[DllImport ("yourdll", EntryPoint ("EE_CognitivSetCurrentLevel")] 
extern static int EE_CognitivSetCurrentLevel2 (int level, int level1, int level2); 

等等......噢,並確保該函數是一個外部的內「C」 {}從而使C++編譯器不裂傷名稱。

2

因爲它是一個C++函數,我假設它具有default parameters.這就是當您用較少的參數調用該函數時,C++編譯器會自動用缺省值填充缺少的參數。 C#不支持默認參數,也不支持從DLL調用。如果是這種情況,那麼你需要找出這些默認參數是什麼,並手動將它們傳入。如果將錯誤的參數數量傳遞給一個函數,最終會出現奇怪的行爲(或者它可以工作,誰知道)。

您可以使用重載在C#提供在C看到相同的行爲++:

class EEFunctions { 
    [DllImport ("yourdll", EntryPoint ("EE_CognitivSetCurrentLevel")] 
    private extern static int EE_CognitivSetCurrentLevelDLL(int level, int level1, 
     int level2, int level3, int level4); 

    private int defaultLevel = 0; // This is just an example 

    public static int EE_CognitivSetCurrentLevel(int level, int level1) { 
     return EE_CognitivSetCurrentLevel(level, level1, 
      defaultLevel, defaultLevel, defaultLevel); 
    } 

    public static int EE_CognitivSetCurrentLevel(int level, int level1, int level2) { 
     return EE_CognitivSetCurrentLevel(level, level1, 
      level2, defaultLevel, defaultLevel); 
    } 

    public static int EE_CognitivSetCurrentLevel(int level, int level1, 
     int level2, int level3) { 
     return EE_CognitivSetCurrentLevel(level, level1, 
      level2, level3, defaultLevel); 
    } 

    public static int EE_CognitivSetCurrentLevel(int level, int level1, 
     int level2, int level3, int level4) { 
     return EE_CognitivSetCurrentLevel(level, level1, 
      level2, level3, level4); 
    } 
} 

這還假定所有的參數都是整數。如果您可以在C++頭文件中找到參數類型的定義,則可以在C#中創建兼容的類型。