C function call in DLL with enumeration parameters from Delphi

I have a third-party (Win32) DLL written in C that provides the following interface:

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

I want to call it from Delphi.

How to access DeviceType constants in my Delphi code? Or, if I just have to use values ​​1 and 2 directly, what type of Delphi should I use for the "Device Type" parameters? Integer? Word?

+4
source share
3 answers

The usual way to declare an interface from an external DLL in C is to open its interface in the .H header file. Then, in order to access the DLL from C, the .H header file must be #include d in the C source code.

Translated into Delphi terms, you need to create a single file that describes the same interface in terms of pascal, translating the c syntax into pascal.

In your case, you will create a file, for example ...

 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. 

And you declare it in the uses your source code. And call the function as follows:

 uses xyzDevice; ... case XyzDeviceStatus(XYZ_DEVICE_USB) of ... 
+6
source

By default, the base type for an enumeration in C ++ is int (unsigned 32 bits). You need to define the same type of parameter in Delphi. Regarding the listed values, you can use hardcoded values ​​1 and 2 to call this function from Delphi or use any other Delphi language function (constant enum? I don't know this language), which gives the same result.

+2
source

Of course, you can use Integer and pass constanst directly, but it is safer to declare a function using the usual enumeration type. It should be like this (pay attention to the "MINENUMSIZE" directive):

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

Source: https://habr.com/ru/post/1307003/


All Articles