Документация
В этом примере показано, как создать библиотеку блоков и добавить его в Simulink ® Library Browser. Этот пример также показывает, как добавить подбиблиотеку.
Чтобы указать информацию о вашей библиотеке, вы создаете функцию с именем slblocks .
Добавьте библиотеку в браузер библиотеки
- От начальной страницы Simulink выберите Blank Library и нажмите Create Library.
Примечание Браузер Библиотеки только поддерживает библиотеки. Вы не можете отобразить содержимое модели в Браузере Библиотеки.
set_param(gcs,'EnableLBRepository','on');
function blkStruct = slblocks % This function specifies that the library 'mylib' % should appear in the Library Browser with the % name 'My Library' Browser.Library = 'mylib'; % 'mylib' is the name of the library Browser.Name = 'My Library'; % 'My Library' is the library name that appears % in the Library Browser blkStruct.Browser = Browser;
Примечание Можно сохранить функцию как .m или .mlx файл. Вы не можете сохранить его как Pcode-файл.

Примечание
Если вы сохраненный ваша библиотека без установки ‘EnableLBRepository’ к ‘on’ , сообщение появляется наверху Браузера Библиотеки.

Нажмите Fix и ответьте на подсказку как соответствующую.
Добавьте подбиблиотеку в браузер библиотеки
Выполните эти шаги, чтобы добавить подбиблиотеку под названием mylib2 к вашему mylib библиотека.
- Создайте библиотеку под названием mylib2 . Добавьте некоторые блоки в него.
- В командном окне MATLAB, набор EnableLBRepository свойство библиотеки к ‘on’ для новой библиотеки.
set_param(gcs,'EnableLBRepository','on');


Задайте порядок библиотеки в списке библиотек
Можно задать порядок библиотеки относительно других библиотек в списке путем добавления sl_customization.m файл к пути MATLAB и установке приоритета вида вашей библиотеки. Например, чтобы видеть вашу библиотеку наверху списка, можно установить приоритет вида на -2 . По умолчанию приоритетом вида Библиотеки Simulink является -1 . Другие библиотеки имеют приоритет вида 0 по умолчанию, и эти библиотеки появляются ниже Библиотеки Simulink. Библиотеки с тем же приоритетом вида появляются в алфавитном порядке.
Это демонстрационное содержимое sl_customization.m файл размещает новую библиотеку наверху списка библиотек.
function sl_customization(cm) % Change the order of libraries in the Simulink Library Browser. cm.LibraryBrowserCustomizer.applyOrder('My Library',-2>); end
Заставить индивидуальную настройку сразу вступить в силу, в командном окне MATLAB, введите:
sl_refresh_customizations

Похожие темы
- Создайте пользовательскую библиотеку
- Настройте внешний вид браузера библиотеки
- Укажите индивидуальные настройки с Simulink
Документация Simulink
- Примеры
- Блоки и другая ссылка
- Информация о релизах
- PDF-документация
Поддержка
- MATLAB Answers
- Помощь в установке
- Отчеты об ошибках
- Требования к продукту
- Загрузка программного обеспечения
© 1994-2021 The MathWorks, Inc.
- Условия использования
- Патенты
- Торговые марки
- Список благодарностей
Для просмотра документации необходимо авторизоваться на сайте
Войти
Памятка переводчика
1. Если смысл перевода понятен, то лучше оставьте как есть и не придирайтесь к словам, синонимам и тому подобному. О вкусах не спорим.
2. Не дополняйте перевод комментариями “от себя”. В исправлении не должно появляться дополнительных смыслов и комментариев, отсутствующих в оригинале. Такие правки не получится интегрировать в алгоритме автоматического перевода.
3. Сохраняйте структуру оригинального текста — например, не разбивайте одно предложение на два.
4. Не имеет смысла однотипное исправление перевода какого-то термина во всех предложениях. Исправляйте только в одном месте. Когда Вашу правку одобрят, это исправление будет алгоритмически распространено и на другие части документации.
5. По иным вопросам, например если надо исправить заблокированное для перевода слово, обратитесь к редакторам через форму технической поддержки.
How to load a c++ dll file into Matlab
I have a C++ dll file that uses a lot of other c++ librarys (IPP, Opencv +++) that I need to load into matlab. How can I do this? I have tried loadlibrary and mex. The load library does not work. The mex finds the linux things (platform independent library) and tries to include them. And that does not work. Does anyone have any good ideas?
124k 25 25 gold badges 244 244 silver badges 456 456 bronze badges
asked Feb 19, 2009 at 13:47
Rolf Anders Rolf Anders
131 1 1 gold badge 1 1 silver badge 8 8 bronze badges
Added C wrappers around the C++ code, and that made the loadlib functions work.
Feb 27, 2009 at 9:43
3 Answers 3
loadlibrary should work. I use it all the time to call functions from dlls written in C++ with C wrappers.
What errors are you getting when you try to use loadlibrary?
Make sure that the exported functions of the dll are C functions, not C++ functions. If not, then write C wrappers.
More info on exactly what you are doing when using loadlibrary would be helpful.
answered Feb 19, 2009 at 17:37
39k 14 14 gold badges 76 76 silver badges 115 115 bronze badges
As mentioned by others, you should first wrap your C++ library as a C library — mathworks used to advise not to use C++ code directly in mex (dlopening C++ core directly is complicated), maybe it is still true.
Your description is quite unclear, too: what do you mean by «mex finds the linux thing», but that does not work. Saying that it does not work is not helpful: the exact commands and error message are.
answered Feb 19, 2009 at 17:49
David Cournapeau David Cournapeau
79k 8 8 gold badges 67 67 silver badges 70 70 bronze badges
You could go for the Java approach (since Matlab runs on a JRE and can access Java objects/methods — just be aware that the Matlab JRE is not as up-to-date as the latest JRE, the one I’m running uses Java 1.5) and use JNA to access your DLL.
Or, if you wrote the top-level DLL, you could go for the COM/ActiveX approach.
I’ve had good success architecting the interface to my C++ functions as COM/ActiveX libraries — you don’t have to bother with that .h stuff.
See the External Interfaces guide on COM clients, particularly the part about managing/converting data.
It would be extra work to add the COM/ActiveX layer, but would make your library more portable within the Windows world and probably more easily used in MATLAB.
If you have a lot of function calls to your DLL, the COM/ActiveX approach might be faster (not sure), but otherwise I think the JNA approach would be easier.
Как добавить библиотеку в матлаб
This example shows how to create a block library and add it to the Simulink ® Library Browser . This example also shows how to add a sublibrary.
To specify information about your library, you create a function named slblocks .
Add Library to Library Browser
- On the Simulink start page, in the search box, type library . Select Blank Library, then click Create Library.
Note The Library Browser only supports libraries. You cannot display the contents of a model in the Library Browser.
set_param(gcs,'EnableLBRepository','on');
function blkStruct = slblocks % This function specifies that the library 'mylib' % should appear in the Library Browser with the % name 'My Library' Browser.Library = 'mylib'; % 'mylib' is the name of the library Browser.Name = 'My Library'; % 'My Library' is the library name that appears % in the Library Browser blkStruct.Browser = Browser;
Note You can save the function as an .m or .mlx file. You cannot save the function as a P-code file.

Note
If you save your library without setting ‘EnableLBRepository’ to ‘on’ , a message appears at the top of the Library Browser.

Click Fix and respond to the prompt as appropriate.
Add Sublibrary to Library Browser
Follow these steps to add a sublibrary named mylib2 to your mylib library.
- Create a library named mylib2 . Add some blocks to it.
- In the MATLAB Command Window, set the EnableLBRepository library property to ‘on’ for the new library.
set_param(gcs,'EnableLBRepository','on');


Specify Library Order in Library List
You can specify the order of your library relative to the other libraries in the list by adding a sl_customization.m file to the MATLAB path and setting the sort priority of your library. For example, to see your library at the top of the list, you can set the sort priority to -2 . By default, the sort priority of the Simulink library is -1 . The other libraries have a sort priority of 0 by default, and these libraries appear below the Simulink library. Libraries with the same sort priority appear in alphabetical order.
This sample content of the sl_customization.m file places the new library at the top of the list of libraries.
function sl_customization(cm) % Change the order of libraries in the Simulink Library Browser. cm.LibraryBrowserCustomizer.applyOrder('My Library',-2>); end
To make the customization take effect immediately, in the MATLAB Command Window, enter:
sl_refresh_customizations
loadlibrary
loadlibrary( libname , hfile ) loads functions from C shared library libname defined in header file hfile into MATLAB ® . The loadlibrary function only supports calling functions that are callable from C and header files that can be parsed by a C compiler. Functions written in C++ must be declared as extern «C» . Alternatively, to call functions in C++ libraries, see Call C++ from MATLAB.
loadlibrary( libname ) loads the library if the name of the header file is the same as the name of the library file.
loadlibrary( libname , hfile , Name,Value ) loads the library with one or more Name,Value arguments.
loadlibrary( libname ,@ protofile ) uses a prototype file, protofile , in place of a header file.
[ notfound , warnings ] = loadlibrary( ___ ) returns warning information, and can include any of the input arguments in previous syntaxes.
Examples
Display Functions in shrlibsample Library
Add path to examples folder.
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
Display functions in library.
if not(libisloaded('shrlibsample')) loadlibrary('shrlibsample') end libfunctions('shrlibsample')
Functions in library shrlibsample: addDoubleRef addMixedTypes addStructByRef addStructFields allocateStruct deallocateStruct exportedDoubleValue getListOfStrings multDoubleArray multDoubleRef multiplyShort print2darray printExportedDoubleValue readEnum stringToUpper
unloadlibrary shrlibsample
Load Library Using Multiple Header Files
Suppose that you have a library, mylib , with the header file, mylib.h . The header file contains the statement, #include header2.h . To use functions defined in header2.h , call loadlibrary with the addheader option.
loadlibrary('mylib','mylib.h','addheader','header2')
Call stringToUpper Function Using Alias Name
if libisloaded('shrlibsample') unloadlibrary('shrlibsample') else addpath(fullfile(matlabroot,'extern','examples','shrlib')) end
Create an alias name lib for library shrlibsample .
loadlibrary('shrlibsample','shrlibsample.h','alias','lib')
Call function stringToUpper using the alias name.
str = 'This was a Mixed Case string'; calllib('lib','stringToUpper',str)
ans = 'THIS WAS A MIXED CASE STRING'
unloadlibrary lib
Search Alternative Paths for Header Files
Add path to folder containing shrlibsample and its header file, shrlibsample.h .
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
The shrlibsample.h header file includes the header file, shrhelp.h . If shrhelp.h is in a different folder, for example, c:\work , use the ‘includepath’ option to tell MATLAB where to find the file.
loadlibrary('shrlibsample','shrlibsample.h','includepath','c:\work')
unloadlibrary shrlibsample
Create Alias Name for shrlibsample Function
This example shows how to replace the addMixedTypes function name in the MATLAB shrlibsample library with an alias name, addTypes . To define the alias name, create a prototype file then load the library using the prototype file as the header file.
Use a folder for which you have write-access.
cd('c:\work')
Create a prototype file, mxproto.m .
hfile = fullfile(matlabroot,'extern','examples','shrlib','shrlibsample.h'); [notfound,warnings] = loadlibrary('shrlibsample',hfile,'mfilename','mxproto')
MATLAB creates the prototype file in the current folder. Ignore the warning messages.
Add the alias name to the prototype file. Open the file in MATLAB Editor.
edit mxproto.m
Search for the function addMixedTypes .
The following statement assigns the alias addTypes .
fcns.alias='addTypes';
Add the statement to the line before the statement to increment fcnNum . The new function prototype, with the new statement shown in bold, looks like the following:
% double addMixedTypes ( short , int , double ); fcns.thunkname='doubleint16int32doubleThunk'; fcns.name='addMixedTypes'; fcns.calltype='Thunk'; fcns.LHS='double'; fcns.RHS=; fcns.alias='addTypes'; % Alias defined fcnNum=fcnNum+1; % Increment fcnNum
Reload shrlibsample using the prototype file.
unloadlibrary shrlibsample loadlibrary('shrlibsample',@mxproto)
Call the function by its alias name.
calllib('shrlibsample','addTypes',int16(127),int32(33000),pi)
ans = 3.3130e+04
unloadlibrary shrlibsample
Input Arguments
libname — Name of shared library
character vector
Name of shared library, specified as a character vector. The name is case-sensitive and must match the file on your system.
On Microsoft ® Windows ® systems, libname refers to the name of a shared library ( .dll ) file. On Linux ® systems, it refers to the name of a shared object ( .so ) file. On Apple Mac systems, it refers to a dynamic shared library ( .dylib ). If you do not include a file extension with the libname argument, loadlibrary attempts to find the library with either the appropriate platform MEX-file extension or the appropriate platform library extension. For a list of MEX-file extensions, use mexext .
MATLAB extracts the name portion of libname to identify the library in other shared library functions. For example, when you call the calllib function, do not include the path or file extension in the library argument name.
Data Types: char
hfile — Name of C header file
character vector
Name of C header file, specified as a character vector. The name is case-sensitive and must match the file on your system. If you do not include a file extension in the file name, loadlibrary uses .h for the extension.
Data Types: char
protofile — Name of prototype file
character vector
Name of prototype file, specified as a character vector. The name is case-sensitive and must match the file on your system. @protofile specifies a function handle to the prototype file. When using a prototype file, the only valid Name,Value pair argument is alias .
Data Types: char
Name-Value Arguments
Specify optional pairs of arguments as Name1=Value1. NameN=ValueN , where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: loadlibrary(‘mylib’,’mylib.h’,’addheader’,’header2′)
addheader — Header file
character vector
Header file, specified as the comma-separated pair consisting of ‘ addheader ‘ and a character vector. Specify the file name without a file extension.
Each file specified by addheader must have a corresponding #include statement in the base header file. To load only the functions defined in the header file that you want to use in MATLAB, use addheader .
MATLAB does not verify the existence of header files and ignores any that are not needed.
alias — Alternative name for library
character vector
Alternative name for library, specified as the comma-separated pair consisting of ‘ alias ‘ and a character vector. Associates the specified name with the library. All subsequent calls to MATLAB functions that reference this library must use this alias until the library is unloaded.
includepath — More search paths for subordinate header files
character vector
More search paths for subordinate header files—header files within header files, specified as the comma-separated pair consisting of ‘ includepath ‘ and a character vector.
mfilename — Prototype file
character vector
Prototype file, specified as the comma-separated pair consisting of ‘ mfilename ‘ and a character vector. Generates a prototype file in the current folder. The prototype file name must be different from the library name. Use this file in place of a header file when loading the library.
thunkfilename — Thunk file
character vector
Thunk file, specified as the comma-separated pair consisting of ‘ thunkfilename ‘ and a character vector. Overrides the default thunk file name.