The Microsoft® Win32® APIs provide control over loading and linking. The LoadLibrary, LoadLibraryEx, and FreeLibrary functions provide explicit control over the loading and freeing of DLLs. The GetProcAddress function allows you to link to a specific export. The GetProcAddress function returns a function pointer, so any language that can call through a function pointer can implement dynamic invocation without a problem.
These functions provide more control over the loading and linking process than the @dll.import directive. For instance, your requirements might include the following:
Microsoft® J/Direct allows you to declare the requisite functions as follows. (If you are using the com.ms.win32 package, these declarations also appear in the Kernel32 class.)
/** @dll.import("KERNEL32",auto) */ public native static int LoadLibrary(String lpLibFileName); /** @dll.import("KERNEL32",auto) */ public native static int LoadLibraryEx(String lpLibFileName, int hFile, int dwFlags); /** @dll.import("KERNEL32",auto) */ public native static boolean FreeLibrary(int hLibModule); /** @dll.import("KERNEL32",ansi) */ public native static int GetProcAddress(int hModule, String lpProcName);
Note GetProcAddress is declared with the ansi modifier, not auto. This is because GetProcAddress is one of the few Microsoft® Windows® functions without a Unicode equivalent. If the auto modifier was used, this function would have failed on Microsoft® Windows NT® systems.
Msjava.dll (the DLL that implements the Microsoft VM) exports a special call function so you can invoke a function obtained by GetProcAddress. The call function's first argument is a pointer to a second function. Call only invokes the second function, passing it the remaining arguments.
For example, the following shows how an application could load a DLL and call a function exported by the DLL.
BOOL AFunction(LPCSTR argument); /** @dll.import("msjava") */ static native boolean call(int funcptr,String argument); int hmod = LoadLibrary("..."); int funcaddr = GetProcAddress(hmod, "AFunction"); boolean result = call(funcaddr, "Hello"); FreeLibrary(hmod);