166. Calling the sumTwoInt() foreign function
Do you remember the sumTwoInt() function? We have defined this C function in a native shared library named math.dll (check Problems 144, 145, and 146). Let’s assume that we have placed the math.dll library in the project folder under the lib/cpp path.
We can call this foreign function in almost the same manner as we’ve called _getpid(). Since math.dll is a user-defined library that is not commonly used, it cannot be loaded via defaultLookup(). The solution is to explicitly load the library from the lib/cpp path, as follows:
Linker linker = Linker.nativeLinker();
Path path = Paths.get("lib/cpp/math.dll");
try (Arena arena = Arena.ofConfined()) {
SymbolLookup libLookup = SymbolLookup.libraryLookup(
path, arena);
...
Next, we have to find in math.dll the foreign function by name. If your C compiler (for instance, G++) has applied the mangling (or name decoration) technique, then sumTwoInt will...