2009-11-18 50 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#中创建兼容的类型。