7
$\begingroup$

I am writing some C++ code that I want to call both through LibraryLink and independently from Mathematica. Thus it must be compatible with LibraryLink but not depend on it.

When calling it from Mathematica, I want to make it abortable.

All LibraryLink functions take an argument WolframLibraryData libData (this is really a pointer). AbortQ is called through it.

Question: Is it safe to cache the value of libData in a global variable, never change it after WolframLibrary_initialize, and use this global variable for calling all LibraryLink functions?

To make the question clearer, this is the layout of my code:

WolframLibraryData libData; // global variable

EXTERN_C DLLEXPORT int WolframLibrary_initialize(WolframLibraryData iLibData) {
    libData = iLibData;
    return LIBRARY_NO_ERROR;
}

class MyClass 
{
public:
    void simulate() {
        for (...) { // long loop
            ...
#ifdef WolframLibraryVersion  // use the global libData here:
            if (libData->AbortQ) { /* abort computation */ }
#endif
        }
    }
}

Cross posted to Wolfram Community.

$\endgroup$
2
  • $\begingroup$ You have code in WolframLibrary_initialize; when is the code actually run? When I call up multiple functions with LibraryFunctionLoad, I find that the code in WolframLibrary_initialize is never really called. $\endgroup$
    – QuantumDot
    Jun 25, 2017 at 16:36
  • $\begingroup$ @QuantumDot I am travelling now, so I am answering from memory. It should run once when the library is first loaded. You do not need to use LibraryLoad to load it. In fact as I remember doing so had harmful effects (problems unloading?). LibraryLoad is only for loading dependencies. Instead use LibraryFunctionLoad only, as usual. The first time you load a function from the library, the initialization should run. $\endgroup$
    – Szabolcs
    Jun 30, 2017 at 4:57

1 Answer 1

2
$\begingroup$

In several projects, I saved the value of libData at library initialization, and used the saved value throughout the lifetime of the library.

So far I have not encountered any problems. Of course that does not mean that there are none.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.