11"""Wrappers for the interface between ratapi and MATLAB custom files."""
22
3+ import os
34import pathlib
45from contextlib import suppress
56from typing import Callable
@@ -20,10 +21,11 @@ def start_matlab():
2021
2122 """
2223 future = None
23- with suppress (ImportError ):
24- import matlab .engine
24+ if os .environ .get ("DELAY_MATLAB_START" , "0" ) == "0" :
25+ with suppress (ImportError ):
26+ import matlab .engine
2527
26- future = matlab .engine .start_matlab (background = True )
28+ future = matlab .engine .start_matlab (background = True )
2729
2830 return future
2931
@@ -39,10 +41,11 @@ class MatlabWrapper:
3941 """
4042
4143 loader = start_matlab ()
44+ loader_error_message = "matlabengine is required to use MatlabWrapper"
4245
4346 def __init__ (self , filename : str ) -> None :
4447 if self .loader is None :
45- raise ImportError ("matlabengine is required to use MatlabWrapper" ) from None
48+ raise ImportError (self . loader_error_message ) from None
4649
4750 self .engine = self .loader .result ()
4851 path = pathlib .Path (filename )
@@ -86,6 +89,30 @@ def handle(*args):
8689 return handle
8790
8891
92+ def use_shared_matlab (name , custom_error_message ):
93+ """Connect asynchronously to shared MATLAB engine instance with the given name.
94+
95+ Parameters
96+ ----------
97+ name : str
98+ The name of shared MATLAB engine instance
99+ custom_error_message : str
100+ The custom error message in case of failed connection
101+
102+ Returns
103+ -------
104+ future : matlab.engine.futureresult.FutureResult
105+ A future used to get the actual matlab engine.
106+
107+ """
108+ with suppress (ImportError ):
109+ import matlab .engine
110+
111+ MatlabWrapper .loader = matlab .engine .connect_matlab (name , background = True )
112+ MatlabWrapper .loader_error_message = custom_error_message
113+ return MatlabWrapper .loader
114+
115+
89116class DylibWrapper :
90117 """Creates a python callback for a function in dynamic library.
91118
0 commit comments