-
Notifications
You must be signed in to change notification settings - Fork 1
Comsol External Function API
An external function is a function defined in a shared library written by the user. The shared library must define the following three functions with C linkage:
-
int init(const char *str) is called when the function is initialized with the string from the Initialization data field. It returns a nonzero value in case of success and zero in case of failure. This function might be called several times; it is always called before solving a model that uses the function
-
int eval(const char *func, int nArgs, const double **inReal, const double **inImag, int blockSize, double *outReal, double *outImag) is called for element-wise evaluation of the function func called with nArgs arguments of length blockSize. The array inReal contains the real parts of the arguments; it has length nArgs, and each element has length blockSize.
If the arguments are all-real, then inImag is null, otherwise it contains the imaginary parts of the arguments. If the function evaluation is successful, 1 is returned if it resulted in an all-real array and 2 is returned if it resulted in a complex array. The function should return 0 in case of error. In case of a real result, the function values should be written to the array outReal. In case of a complex result, the real parts of the function should be written to outReal and the imaginary parts to outImag. The outReal and outImag arrays both have length blockSize. All matrices are allocated and deallocated by Multiphysics.
- const char *getLastError() returns the last error that has occurred. A null or empty string is returned if no error has occurred. Calling init() or eval() must set the last error string to "". All memory allocation of this string is handled by the shared library. There is no localization of the error messages.
An example of a library that defines a function called extsinc that computes the sinc function:
#include <math.h>
#include <stdlib.h>
#include <string.h>
static const char *error = NULL;
int init(const char *str) {
return 1;
}
const char * getLastError() {
return error;
}
int eval(const char *func,
int nArgs,
const double **inReal,
const double **inImag,
int blockSize,
double *outReal,
double *outImag) {
int i, j;
if (strcmp("extsinc", func) == 0) {
if (nArgs != 1) {
error = "One argument expected";
return 0;
}
for (i = 0; i < blockSize; i++) {
double x = inReal[0][i];
outReal[i] = (x == 0) ? 1 : sin(x) / x;
}
return 1;
}
else {
error = "Unknown function";
return 0;
}
}
Source: Comsol API Documentation