代码之家  ›  专栏  ›  技术社区  ›  dommer

使用Delphi的枚举参数调用dll中的C函数

  •  4
  • dommer  · 技术社区  · 15 年前

    我有一个用C编写的第三方(win32)dll,它公开了以下接口:

    DLL_EXPORT typedef enum
    {
      DEVICE_PCI = 1,
      DEVICE_USB = 2
    } DeviceType;
    
    DLL_EXPORT int DeviceStatus(DeviceType kind);
    

    我想从德尔福打电话过来。

    如何访问Delphi代码中的deviceType常量?或者,如果我应该直接使用值1和2,我应该为“devicetype kind”参数使用什么delphi类型?整数?单词?

    3 回复  |  直到 15 年前
        1
  •  6
  •   PA.    15 年前

    在C中从外部dll声明接口的通常方法是在.h头文件中公开其接口。然后,要从C访问dll,.h头文件必须 #include 在C源代码中。

    翻译成delphi术语后,您需要创建一个用pascal术语描述相同接口的单元文件,将C语法翻译成pascal。

    对于您的案例,您将创建一个文件,例如…

    unit xyzDevice;
    { XYZ device Delphi interface unit 
      translated from xyz.h by xxxxx --  Copyright (c) 2009 xxxxx
      Delphi API to libXYZ - The Free XYZ device library --- Copyright (C) 2006 yyyyy  }
    
    interface
    
    type
      TXyzDeviceType = integer;
    
    const
      xyzDll = 'xyz.dll';
      XYZ_DEVICE_PCI = 1;
      XYZ_DEVICE_USB = 2;
    
    function XyzDeviceStatus ( kind : TXyzDeviceType ) : integer; stdcall; 
       external xyzDLL; name 'DeviceStatus';
    
    implementation
    end.
    

    你会在 uses 源代码的子句。并以这种方式调用函数:

    uses xyzDevice;
    
    ...
    
      case XyzDeviceStatus(XYZ_DEVICE_USB) of ...
    
        2
  •  2
  •   Alex F    15 年前

    C++中枚举的默认基础类型是int(未签名的32位)。您需要在Delphi中定义相同的参数类型。对于枚举值,可以使用硬编码的1和2值从Delphi调用该函数,或者使用任何其他Delphi语言特性(Enum?常数?我不懂这门语言),结果是一样的。

        3
  •  1
  •   Alex    15 年前

    当然,可以使用integer并直接传递constanst,但使用通常的枚举类型声明函数更安全。应该是这样的(注意“minenumsize”指令):

    {$MINENUMSIZE 4}
    
    type
      TDeviceKind = (DEVICE_PCI = 1, DEVICE_USB = 2);
    
    function DeviceStatus(kind: TDeviceKind): Integer; stdcall; // cdecl?