To use a library in your application, you need to call it from a method or a utility class. Use the External external(String libraryTag) method available in the
ApplicationMethod class or the
ApplicationLanguageBase class. It returns an object of type
External with the following methods:
which assumes a C function declared as int stringLength(char *str). Alternatively, you could use the following code:
which assumes a C function declared as int sum(int a, int b). The latter syntax is more efficient if you need to make several calls to the same library.
For arguments of type String[], the program can modify a pointer in the array of pointers to point to a new null-terminated string, which is transferred back to Java. The maximal allowed length of a string is 65,535 characters. Use a byte array to transfer larger amounts of data. It is possible to return a null value to Java by setting the corresponding element in the string array to
0.
The external function can return an integer (int) or a pointer to some internal object (
void *). In Java, this value is returned as a long value, which is sufficiently wide to hold a 64-bit memory address. If you need a
String or a
double as return value, you must instead pass an array of length one and the right type, which can be filled in by the external function.
It may be possible to use a native code debugger (like Microsoft Visual Studio®) when working with applications. First, you need to build the library with debug symbols. Then you import this library into the application, and attach the debugger to the COMSOL process. Put a break point in the native function that you want to debug. Run or test run the application in COMSOL Multiphysics. When COMSOL Multiphysics loads the external library, the debugger should be able to match the source code where you put your breakpoint with the loaded library and to break when the function is called. Please refer to the documentation of your native debugging system for further details.
The source code below defines a trivial external function written in C++, which you want to call. The #ifdef statement is intended to make the source code cross-platform compatible, but writing a shared library typically involves compiler-specific settings, so you may need to consult the documentation of your compiler. The header file,
test.h, is as follows:
Add an External C Library node, with tag
native1, and import the library created in Step 1 for the right platform.
Add a button to the form, and choose the method added above as the command to execute. If you are building the application on the same platform the library is built for, you can click Test Application to test run the method. Otherwise, save the application and run it in a COMSOL Multiphysics session on the correct platform. In any case, when you press the button in the application window, you should see a dialog stating a truism.