Some Microsoft® Win32® functions declare a parameter whose type depends on the value of another parameter. For example, the WinHelp function is declared as follows:
BOOL WinHelp(int hwnd, LPCTSTR szHelpFile, UINT cmd, DWORD dwData);
The dwData parameter can be any one of the following, depending on the value of the cmd parameter: a pointer to a String, a pointer to a MULTIKEYHELP structure, a pointer to a HELPWININFO, or a plain integer.
J/Direct offers two ways to declare such a parameter:
This section shows how to declare WinHelp by declaring dwData as type Object.
/** @dll.import("USER32") */ static native boolean WinHelp(int hwnd, String szHelpFile, int cmd, Object dwData);
When WinHelp is invoked, J/Direct will use the runtime type to determine how to translate dwData. The following table describes how the types are translated.
Type |
Translated as |
java.lang.Integer | 4-byte integer. |
java.lang.Boolean | 4-byte BOOL. |
java.lang.Char | CHAR (or WCHAR if the unicode or ole modifiers are in effect). |
java.lang.Short | 2-byte SHORT. |
java.lang.Float | 4-byte FLOAT. |
java.lang.String | LPCSTR (or LPCWSTR if the unicode or ole modifier is in effect). |
java.lang.StringBuffer | LPSTR (or LPWSTR if the unicode or ole modifier is in effect). |
byte[] | BYTE*. |
char[] | CHAR* (or WCHAR* if the unicode or ole modifier is in effect). |
short[] | SHORT*. |
int[] | INT*. |
long[] | __int64. |
float[] | float*. |
double[] | double*. |
@dll.struct | pointer to structure. |
Another way to declare the WinHelp function is to overload the function for each possible type as shown in the following example.
/** @dll.import("USER32") */ static native boolean WinHelp(int hwnd, String szHelpFile, int cmd, int dwData); /** @dll.import("USER32") */ static native boolean WinHelp(int hwnd, String szHelpFile, int cmd, String dwData); /** @dll.import("USER32") */ static native boolean WinHelp(int hwnd, String szHelpFile, int cmd, MULTIKEYHELP dwData); /** @dll.import("USER32") */ static native boolean WinHelp(int hwnd, String szHelpFile, int cmd, HELPWININFO dwData);
A polymorphic return value cannot be handled using overloading because Java methods cannot be overloaded only on their return values. Therefore, give each variant of the function a different Java name and use the entrypoint modifier to link them all to the same DLL method. To learn more about renaming DLL methods, see Aliasing (Method Renaming).