Verifier DLL in DLL Description
Void dllname01 (void) @ dllname01 $ qv because it is a CPP code
void _stdcall dllname02 (void) @ dllname02 $ qsv so the letter name is repaired
Void _cdecl dllname03 (void) @ dllname03 $ qv decorated.
Void _Pascal Dllname04 (Void) @ DLLNAME04 $ qv
void _fastcall dllname05 (void) @ dllname05 $ qqrv
The above results make you twilight two gold steel, you can't touch your hair. This is because our program name is expressed in CPP, C Builder will name the C unique naming method, this name mode will add the nature of the use parameters after the letter name, such as Parameter category, etc. This has a special name in C , called Mangled Name, which is a naming rule issued to make multiple load functions. (Note: Add (int) and add (double) in C can exist at the same time, so you must distinguish between Object Code). At the same time, this naming method is different because of the various compiler manufacturers, so avoid use when writing DLLs. In order to avoid the above problems, we will change the way the following declaration:
#define _dllname01_h_
#ifndef dllname
#define extern __DECLSPEC (DLLIMPORT)
#ELSE
#define extern __DECLSPEC (DLLEXPORT)
#ENDIF
Extern "C" {
Extern void dllname011 (void);
Extern void _stdcall dllname022 (void);
Extern void _cdecl dllname033 (void);
Extern void _pascal dllname044 (void);
Extern void _fastcall dllname055 (void);
}
#ENDIF
Where Extern "C" {琕琕.}; Is used to tell the compiler to use C named: Do not use C mangled name. If there is only one group, you can declare it directly below:
EXTERN "C" void __stdcall showimage ();
Now we can view the letter name after removing mangled name:
Verifier DLL in DLL Description
Void dllname01 (void) _dllname01 name plus bottom line
Void _stdcall dllname02 (void) Dllname02 name is not changed
Void _cdecl dllname03 (void) _dllname03 name plus bottom line
Void _Pascal Dllname04 (Void) Dllname04 name uppercase
void _fastcall dllname05 (void) @ dllname05 name plus @
We can know above that the name when using the _cDecl modifies when not adding the word. _Pascal modified words generated by the word name and the 16-bit standard DLL letter name (which is not accepted in VC ), __ fastcall's word name plus @.
Among them, the most used in Win32 is _stdcall modifies, this is also the modified word you want to write when you can use it together with other languages, followed by __cdecl modifier, which is used to transmit non-parameter type Letters such as Printf, Sprintf, etc. are used. The other two have no chance to use in the DLL. in conclusion:
From the above, you must pay attention to the following items when writing a DLL in C Builder:
Use __Declspec (dllimport) and the standard type of __Declspec (dllexport).
1. Note that the C letter name encoding is encoded (Mangled Name).
2. Pay attention to the use of modified words. The __stdcall modifier word must be used unless the use of the uncertain parameters is used.
(4) Do not confuse the use of __Declspec and __stdcall. This two has no absolute correlation. Even the program may be planted here, remember, remember!
How, after reading the above introduction, is there a feeling of swaying aware. After understanding the above rules, you should not fall you when you write or use the DLL, you should not fall!
Finally, we are listed in the standard DLL declaration to deepen your impression:
#ifndef _showimg_h_
#define _ShowImg_h_
#ifndef imgdll
#define extern __DECLSPEC (DLLIMPORT)
#ELSE
#define extern __DECLSPEC (DLLEXPORT)
#ENDIF
EXTERN "C" extern void __stdcall showimage (void);
#ENDIF
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
Language Shuangxiong 'C Builder and Visual C
As we have written on the matters that write a DLL on C Builder, let's talk about another focus - C Builder and Visual C links. If you don't use Visual C , you can ignore this part. If you need to use the Visual C DLL or you must provide DLL to VC or VB, you may bring you unexpected gain.
VC uses C Builder DLL Versions
The use of C Builder's DLL in Visual C and the use of Datong in C Builder, only a few things must be noted.
(1) Visual C LIB file format and C Builder's lib format, so you have to re-generate a lib. However, unfortunately, the version of VC did not provide an Implib.exe in the 32-bit version (this has not been made to many people, so you can't make it easy to generate lib files. Solutions There are two: one of them writes an empty DLL function in VC , which makes it generated by LIB files, which is the use of LoadLibrary, GetProcAddress, clear call mode.
(2) Use the standard readings mentioned earlier.
C Builder uses VC DLL Verstries to use VC DLL in C Builder to note the special naming rules used in Visual C when C Builder. In addition to the few items mentioned earlier in VC , it also uses a special parameter nomenclature. In short, it is the size of the parameter after the function name, this naming method will cause C The troubles of Builder, VB, Delphi use. for example
Extern "C" _Declspec (dllexport) Void __stdcall showimage (void);
The word name generated in VC is showimage @ 0 (where 0 means the parameter size), rather than ShowImage, which is generated in C Builder, this is a VC known issue, this problem has also caused a lot of use NON- The problem of VC users, the solution is to add the following narrative in the DEF file of the DLL
Exports
Showimage = showimage @ 0
This can create the correct written name. If you don't want to modify the DEF file, you can also add the following link guidelines in the program.
#pragma Comment (Linker, "/ Exports: showimage = showimage @ 0))
Suppose you don't sure its correct name, you can use Dumpbin or TDUMP observation.
The above is an additional description for the program of VC . Finally, we call the About Dialog DLL of this unit with a VC program.
The key prices of this program are as follows:
Void CvCusedllapp :: onappabout ()
{
Void (* showimage) (void);
Hinstance hinst;
Hinst = loadingLibrary ("dllsamp2.dll");
(FarProc &) ShowImage = GetProcaddress (HinSt, "Showimage");
ShowImage ();
Freelibrary (HINST);
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
Export C Functions for Use In C or C Language Executables
Home | OVERVIEW | How do I | FAQ | Details | Sample
If you have functions in a DLL written in C that you want to access from a C-language or C - language module, you should use the __cplusplus preprocessor macro to determine which language is being compiled, and then declare these functions with C linkage if being used from a C -. language module If you use this technique and provide header files for your DLL, these functions can be used by C and C users with no change.The following code shows a header file which can be used by C and C Client Applications:
// mycfuncs.h
#ifdef __cplusplus
Extern "C" {// ONLY NEED TO EXPORT C Interface IF
// use by C Source Code
#ENDIF
__DECLSPEC (DLLIMPORT) VOID Mycfunc ();
__Declspec (dllimport) void anothercfunc ();
#ifdef __cplusplus
}
#ENDIF
If you need to link C functions to your C executable and the function declaration header files have not used the above technique, in the C source file, do the following to prevent the compiler from decorating the C function names:
Extern "C" {
#include "mycHeader.h"
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
How do I Share Data IN My DLL WITH AN Application Or WITH OTHER DLLS?
Home | OVERVIEW | How do I | FAQ | Details | Sample
Win32 DLLs are mapped into the address space of the calling process. By default, each process using a DLL has its own instance of the DLL global and static variables. If your DLL needs to share data with other Win32 DLLs loaded by a different application or WITH DIFFERENT MAPPINGS OF THE SAME DLL, THEN You Can CAN Use Either of the Following Approaches:
CREATE NAMED DATA Sections Using The #pragma Statement.
· Use memory-mapped files.
To set up a new named section, use the #pragma data_seg directive. You then must specify the correct sharing attributes for this new named data section in your .DEF file. For more information about creating named data sections, see the following Knowledge Base articles :
· "How to share data between diffreent mappings of a dll" (Q125677).
· "Specifying Shared and Nonshared Data IN A DLL" (Q100634).
· "How to Specify Shared and Nonshared Data IN A DLL" (Q89817).
· "Sharing All Data In A DLL" (Q109619).
However, if you need to Share A C Class Instance, You Should Use A Memory-mapped file, Because Each Time A Process AttaChes To The DLL, The Constructor for the Object IS Called. For Example:
#pragma data_seg (". myseg")
_DECLSPEC (DLLEXPORT) CTEST Counter1 (0);
_Declspec (dllexport) short counter2 = 0;
#pragma data_seg ()
Assume that the variables Counter1 and Counter2 are incremented in a function in the DLL. The value of Counter2 increases as expected, but on each process attach, the constructor for Counter1 is called reinitializing it to zero. In order to share Counter1, you must use A Memory-Mapped File. for more information about memory-mapped files, see file mapping in the win32 sdk documentation
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
Using __DECLSPEC (DLLIMPORT) AND __DECLSPEC (DLLEXPORT)
Home | OVERVIEW | How do I | FAQ | Details | Sample
The 32-bit edition of Visual C uses __declspec (dllimport) and __declspec (dllexport) to replace the __export keyword previously used in 16-bit versions of Visual C . You do not need to use __declspec (dllimport) for your code to compile correctly , but doing so allows the compiler to generate better code. The compiler is able to generate better code because it knows for sure whether a function exists in a DLL or not, so the compiler can produce code that skips a level of indirection that would normally BE Present in A Function Call That Cross A DLL Boundary. However, You Must Use__declspec (dllimport) in Order To Import Variables Used In A DLL.
With the proper .DEF file EXPORTS section, __declspec (dllexport) is not required. __Declspec (dllexport) was added to provide an easy way to export functions from an .EXE or .DLL without using a .DEF file.
The Win32 Portable Executable format is designed to minimize the number of pages that must be touched to fix imports. To do this, it places all the import addresses for any program in one place called the Import Address Table. This allows the loader to modify only OR TWO Pages When Accessing these Imports.
Using _Declspec (DLLIMPORT) for Function Calls
In The Following Code Example, Assume Func1 IS A Function That Resides in A DLL Separate from The .exe File That Contains The Main Function.
WITHOUT __DECLSPEC (DLLIMPORT), GIVEN THIS CODE:
Void main (void)
{
Func1 ();
}
The Compiler Generates Code That Looks Like this:
Call func1
And the Linker Translates The Call Into Something Like this:
Call 0x4000000; The Address of 'Func1'.
If func1 exists in another DLL, the linker can not resolve this directly because it has no way of knowing what the address of func1 is. In 16-bit environments, the linker adds this code address to a list in the .EXE that the Loader Would Patch At Run Time with The Correct Address. In 32-Bit Environments, The Linker Generates A Thunk of Which It Does Know The Address. The Thunk Looks Like: 0x40000000: JMP DWORD PTR __IMP_FUNC1
Here __imp_func1 is the address for func1's slot in the import address table of the .EXE file. All the addresses are thus known to the linker. The loader only has to update the .EXE file's import address table at load time for everything to work correctly .
Therefore, using __declspec (dllimport) is better because if the linker does not generate a thunk if it is not required. Thunks make the code larger (on RISC systems, it can be several instructions) and can degrade your cache performance. If you tell The Compiler The Function IS in A DLL, IT CAN Generate An Indirect Call for you.
So Now this code:
__DECLSPEC (DLLIMPORT) Void Func1 (Void);
Void main (void)
{
Func1 ();
}
Generates this instruction:
Call dword PTR __IMP_FUNC1
The 'is no thunk and no jmp instruction, so the code is smaller and faster.
On the other hand, for function calls inside a DLL, you do not want to have to use an indirect call. You already know a function's address. Time and space is required to load and store the address of the function before an indirect call , so a direct call is always faster and smaller. You only want to use __declspec (dllimport) when calling DLL functions from the outside the DLL itself. Do not use __declspec (dllimport) on functions inside a DLL when building that DLL.
Using _declspec (dllexport) Microsoft introduced __export in the 16-bit compiler version of Visual C to allow the compiler to generate the export names automatically and place them in a .LIB file. This .LIB file could then be used just like a static. Lib to Link with a dll.
Microsoft Added __Declspec (DLLEXPORT) to Continue this Convenience. Its Purpose Is To Add The Export Directive To The Object File So you don't need NEED A .def file.
This convenience is most apparent when trying to export decorated C function names. There is no standard specification for name decoration, so the name of an exported function may change between compiler versions. If you use __declspec (dllexport), recompiling the DLL and dependent. EXE Files Is Necessary Only to Account for Any Naming Convention Changes.
Many export directives, such as ordinals, NONAME, and PRIVATE, can be made only in a .DEF file, and there is no way to specify these attributes without a .DEF file. However, using __declspec (dllexport) in addition to using a .Def file does not cause build errors.
As a reasonence, Search Through the win32 winbase.h header file. It contacts examples of __declspec (dllimport) usage.
Using __DECLSPEC (DLLEXPORT) AND __DECLSPEC (DLLIMPORT) ON DATA
In the case of data, using __declspec (dllimport) is a convenience item that removes a layer of indirection. When you import data from a DLL, you still have to go through the import address table. In the Win32 days before __declspec (dllimport) This Meant You Had to Remember To Do An Extra Level of Indirection When Accessing Data Exported from The DLL:
// Project.h
#ifdef _dll // if Accessing the data from inside // the dll
Ulong Uldataindll;
#ELSE // if Accessing The data from // outside the dllulong * Uldataindll;
#ENDIF
You Would THEN EXPORT The Data in Your .def File:
// Project.def
Library Project
Exports
Uldataindll Constant
And Access It Outside the DLL:
IF (* Uldataindll == 0L)
{
// Do Stuff Here
}
When you mark the data as __declspec (dllimport), the compiler automatically generates the indirection code for you. You no longer have to worry about the steps above. As stated previously, do not use __declspec (dllimport) declaration on the data when building the DLL. Functions WITHIN THE DLL WILL NOT USE The Import Address Table To Access The Data Object; The Rera Level of Indirection Present.
To Export The Data Automatically from The DLL, Use this Declaration:
__declspec (dllexport) Ulong Uldataindll;
Using a .def file
If you choose to use __declspec (dllimport) Along with a .def file, you Should Change the .def File to use data in place of constant to reduce the likelihood That Incorrect Coding Will Cause A ProBLEM:
// Project.def
Library Project
Exports
Uldataindll Data
The Following Table shows why:
Keyword
Emits in the import librage
Exports
CONSTANT
_imp_uldataindll_uldataindll
_ULDATAINDLL
Data
_imp_uldataindll
_ULDATAINDLL
Using __declspec (dllimport) and CONSTANT lists both the __imp_ version and the undecorated name in the .LIB DLL import library that is created to allow explicit linking. Using __declspec (dllimport) and DATA lists just the __imp_ version of the name.
If you use constant, Either of the folload code constructs could be used to access the Uldataindll:
__Declspec (dllimport) ulong uldataindll; / * prototype * /
IF (Uldataindll == 0L) / * Sample Code Fragment * / - OR-
Ulong * Uldataindll; / * prototype * /
IF (* Uldataindll == 0L) / * Sample Code Fragment * /
However, if you use data in your .def file, "ONLY CODE) CON Access The Variable Uldataindll:
__Declspec (dllimport) Ulong Uldataindll;
IF (Uldataindll == 0L) / * Sample Code Fragment * /
Using CONSTANT is more risky because if you forget to use the extra level of indirection, you could potentially access the import address table's pointer to the variable -. Not the variable itself This type of problem can often manifest as an access violation because the import address Table is currently name read-only by the microsoft compiler and linkers.
The Current Visual C linker issues a warning if it sees CONSTANT in the .DEF file to account for this case. The only real reason to use CONSTANT is if you can not recompile some object file where the header file did not list __declspec ( DLLIMPORT) on the protoype.
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
These macros you have encountered are for conditional compilation. Under normal circumstances, all rows in the source program participate in compilation. However, sometimes it is desirable to compile some of the contents only in order to meet certain conditions, which is the condition specified for a part of the content, which is "conditional compilation". Sometimes it is desirable to compile a group of statements when a condition is met, and another group of statements is compiled when the conditions are not met. The most common form of conditional compile command is: #IFDEF Identifier Procedure 1 #Else block 2 #ENDIF It is: When the identifier has been defined (generally using #define command definition), the block 1 Compile, otherwise the program segment 2 is compiled. The #else section can also be no, ie: #ifdef block 1 #denif here "block" can be a statement group or a command line. This condition is compiled to improve the versatility of the C source program. If a C source program runs on the system on different computer systems, different computers have a certain difference. For example, we have a data type. In the Windows platform, we should use the long type representation, and in other platforms should use FLOAT to indicate, this often requires the necessary modifications to the source program, which reduces the versatility of the program. You can compile the following conditions: #ifdef window #define mytype long #else #EnDePe Float #Endif If you compile the program on Windows, you can compile the following command line: #define on the start of the program: #define MyType Long If the following command line appears before this set of conditions: #define windows 0, the Mytype in the program is replaced with Float. In this way, the source program can be used for different types of computer systems without any modifications. Of course, the above is only a simple case, and other conditions can be designed according to this idea. For example, when debugging a program, it is often desirable to output some of the information required, and this information is no longer output after debugging. You can insert the following conditional compilation segments in the source program: #ifdef debug print ("Device_open (% P) / N", File); #ENDIF If there is the following command line in it: #define debug is running at the program Output the value of the File pointer to debug analysis. Simply delete this define command line after debugging. Some people may think that it is not necessary to compile it, that is, add a batch of printf statements when debugging, remove the printf statement one by debugging. Indeed, this is ok. However, when debugging, the PrintF statement is more time, the modified workload is very large. With conditional compilation, you don't have to delete the printf statement one by one, just remove a "#define debug" command in front, all of which makes all of the DEBUG identifiers to do not work. The role of unified control, like a "switch". Sometimes the following form: #ifndef identifier program segment 1 #ELSE block 2 #ENDIF is only the first line with the first form: "IFDEF" is changed to "IFNDEF".
Its role is to compile the program segment 1 if the identifier is not defined, otherwise the compile block 2. This form is opposite to the first form. The above two types of usage is similar, and one is optionally optionally, depending on the convenience. There is also a form, that is, #iF is an expression instead of a simple identifier: #IF expression block 1 #Else block 2 #ENDIF its role is: When the specified expression value is true (Non-zero), the program segment 1 is compiled, otherwise the program segment 2 is compiled. You can give a certain condition in advance to make the program perform different functions in different conditions. For example: Enter a line of alphabet characters, set the condition as needed, so that the letters are all changed to uppercase output, or all changed to lowercase letters. #define letter 1 main () {char str [20] = "c language", c; int i = 0; while ((c = STR [i])! = '/ 0') {i ; #if letter if (C> = 'a' && c <= 'z') c = c-32; #ELSE IF (c> = 'a' && c <= 'z') c = c 32; #ndif printf ("% C) ", c);}} The result is: c LANGUAGE now defines letter to 1, so when the pre-processing condition is compiled, because the letter is true (non-zero), the first IF statement is compiled, running Change your lowercase letters. If the program first row is changed to: #define letter 0, the second IF statement is compiled, so that the uppercase letters become lowercase letters (uppercase letters and corresponding lowercase letters ASCII code difference 32) . At this time, the operating situation is: c Language will ask: Can you use the IF statement directly without the conditional compilation command, what is the benefit of using the conditional compile command? Indeed, this problem can be completely compiled without conditional compilation, but doing the target program length (because all statements are compiled), and the conditional compilation can reduce the compiled statement, thereby reducing the length of the target. When the conditional compilation segment is more, the target program length can be greatly reduced. $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
Let's take a look at the common preprocessing instructions: #define macro definition #Undef Undefined Macro #include text contains #ifDef If the macro is defined to compile #ifndef If the macro is not defined, the compiling #ENDIF ends the compiling block control # If the IF expression is non-zero, compiling the code #else as the remaining options for other prerequisites. #LIF This is a combination of #LINE to change the current number of rows and file name #Error output an error Information #pragma provides unconventional control information for compilers $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$
Subject: Re: How to pass parameters to a dll generated from matlab ???
Author: lepha
Date: Thu, 4 Mar 2004 23:52:27 -0500
Hi,
Suppose you have a function in m-file, mysquare.m. After you
Generated mysquarelib.dll, you can call your function as stock:
Double CalculateMysquare (double x) {
MxArray * x_ptr;
MxArray * y_ptr;
Double * pval;
/ * CREATE A MXAARRAY TO INPUT INTO MLFMYSQUARE (..) Function * /
X_ptr = mlfscalar (x);
/ * Call the initial function * /
mysquarelibinitialize ();
/ * Call The Implementation FUNCTION * /
y_ptr = mlfmysquare (x_ptr);
/ * Call The Termination Function * /
mysquarelibterminate ();
/ * Return Value from mlfmysquare (..) IS A MxArray, So WE
Will Translate to C Type * /
PVAL = mxgetpr (y_ptr);
Double y = * pval;
Return Y;
}
More of Details Are IN OUR Book, Matlab C / C , in
Www.lephapublishing.com
Hope it helps.
Lephan,
Tunayu Wrote:
>>
> Hello!,
> I Have Made A DLL File from Matlab, SO As To I Can Call IT IN A
> VC Enviroment, HoWever, I don't know the detail data strcture of
> the
> so-caled "marray-tab", SO i failed to pass parametere to the dll
> .Is
> There Someone Here Can Help Me? Urgent !!!!!!> FOLLOWING IS My M-Function:
> Function F = DD (x)
> f = x. ^ 2;
> How can I call A DLL FILE MADE from THID M-FUNCTION ???????
> CAN you give me any help ??????
> Thanks a lot !!!!!!!!!
> YOURS
> Tunayu
>
>
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
Introduction
Some times it is required that we build a shared library (DLL) from an m-file. M-files are functions that are written in Matlab editor and can be used from Matlab command prompt. In m-files, we employ Matlab built- in functions or toolbox functions to compute something. in my past articles, I showed you some ways to use Matlab engine (vis. API, C class or Matlab engine API) for employing Matlab built-in functions, but what about functions that we develop ? How can we use the the. Is there..........................
Shared Libraries
Shared Libraries or Dlls Are Files That Exported Functions in Any Language. Here IS A BRIEF INSTRUCTION TO BUILD SHARED LIBRARIES from MATLAB M-FILES:
1. Compile Your M-File Into A DLL (from Matlab Command Prompt):
MCC -T -L C -W LIB: MYLIB -T LINK: LIB --H
The -t option tells the Matlab compiler to translate the m-file to the target language. The -L option specifies the target language, which is chosen to be C. The -W option tells the Matlab compiler to build a wrapper for the library with the name specified by "lib:"... The -T option tells the compiler what stage should be reached and for what intentions Here we link our application together to build a shared library (DLL) Specifying libmmfile.mlib tells Matlab compiler to Link Against Matlab M-File Math Routine.This Step Will Produce MYLIB.DLL, MYLIB.LIB and MyLib.h. for debugging purposes, you can add the -g switch to produce a dll suitable for debugging in msvc.
For Example, I wrote my own mean function and saved it as meanfunction.m:
Function Y = meanfunction (x)
[m, n] = size (x);
K = 0;
For i = 1: n
K = k x (i);
end
Y = k / n;
And Compiled It with MCC:
MCC -T -L C -W LIB: meanfunctionLib -t link: lib meanfunction.m libmmfile.mlib
2. Create your project in VC. In your main CPP file, include your function header file and add the related library. Here I create a simple console application. Make sure to call initialization and termination routines from your code before and after of calling the M-file function.
3. #include "stdafx.h"
4. â #include "matlab.h"
5. #include "meanfunctionLib.h"
6.
7. #pragma Comment (Lib, "Libmx.lib")
8. #pragma Comment (lib, "libmatlb.lib")
9. #pragma Comment (lib, "libmat.lib")
10. #pragma Comment (Lib, "Libmmfile.lib")
11. #pragma Comment (Lib, "MeanfunctionLib.lib")
12.
13. INT Main (int Argc, char * argv []) 14. {
15. MxArray * Result;
16. mxaRray * x;
17. Double MyArray [5] = {10.2, 3, 6.3, 5.4, 5.9};
18.
19. x = MXcreatedoublemtrix (1, 5, mxreal);
20. Memcpy (MxgetPR (X), MyArray, 5 * sizeof (double));
twenty one.
22. MeanfunctionLibinitialize ();
twenty three.
24. Result = mlfmeanfunction (x);
25.
26. MeanFunctionLibterminate ();
27.
28. mlfprintMatrix (Result);
29.
30. MXDESTROYARRAY (X);
31. MXDESTROYARRAY (RESULT);
32.
33. RETURN 0;
}
34. Build Your Project.
Notice That You Must Use Matlab C API or Matlab C Class Library To Use MxArray Or Mwarray. For more information, refer to my articles:
SOLVING ENGINEERING Problems Using Matlab C API
Solving Engineering Problems Using Matlab C MATH LIBRARY
Enjoy!
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
Loading and unloading the library
To give MATLAB access to external functions in a shared library, you must first load the library into memory. Once loaded, you can request information about any of the functions in the library and call them directly from MATLAB. When the library is no longer needed YOU WILL NEED TO UNLOAD IT from Memory To Conserve Memory Usage.
Loading the library
To load a shared library Into matlab, use the loadinglibrary function. The Syntax for loadingLibrary IS
· LoadLibrary ('shrib', 'hfile')
where shrlib is the filename for the .dll shared library file, and hfile is the filename for the header file that contains the function prototypes. See the reference page for loadlibrary for variations in the syntax that you can use.Note The header file provides signatures For the functions in the library and is a required argument for loadinglibrary.
As an example, you can use loadlibrary to load the libmx library that defines the MATLAB mx routines. The first statement below forms the directory specification for the matrix.h header file for the mx routines. The second loads the library from libmx.dll, Also Specifying The Header File:
· Hfile = [matlabroot '/extern/include/matrix.h'];
· LoadLibrary ('libmx', hfile)
There Are Also Several Optional Arguments That You Can Use with loadLibrary. See The loadLibrary Reference Page for more information.
Unlineing the library
To unload the library and free up the memory That it ipcupied, us the unloadlibrary function. For example,
· UnloadLibrary Libmx
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$
Introduction
As all of you know, MATLAB is a powerful engineering language. Because of some limitation, some tasks take very long time to proceed. Also MATLAB is an interpreter not a compiler. For this reason, executing a MATLAB program (m file) is time consuming. For solving this problem, Mathworks provides us C Math Library or in common language, MATLAB API. A developer can employ these APIs to solve engineering problems very fast and easy. This article is about how can use these APIs.
Matrix Laboratory
.. MATLAB is abbreviation of Matrix Laboratory This means every computation was performed in matrix form In other hand every data type wrapped in matrix form and every functions take these matrix as input argument.For example you want to multiply to polynomial as follow: A = (3x2 5X 7) (4x5 3x3 - x2 1)
You can use two matues for coefficients of any polynomials:
[3 5 7] for (3x2 5x 7) and [4 0 3 -1 0 1] for (4x5 3x3 - x2 1), Using Conv Function, We can Obtain Coefficients of Result: conv ([3 5 7], [4 0 3 -1 0 1]):
A = [12 20 37 12 16 -4 5 7]
Means: a = 12x7 20x6 37x5 12x4 16x3 - 4x2 5X 7
C Math Library
The functions fall into two groups: the mathematical functions and the utility functions We use mathematical functions for computing and utility functions for constructing an array or matrix or printing content of a matrix Every matrices represented by mxArray a data type introduced by MATLAB for constructing.. A Matrix. As I Said Before, Every Data Must Be Wrapped in A Matrix Form in Other Hand: MxArray
One C prototype supports all the possible ways to call a particular MATLAB C Math Library function. You can reconstruct the C prototype by examining the MATLAB syntax for a function. In the following procedure, the MATLAB function svd () and the corresponding library function mlfSvd () Are used to illustrate the process.
Matlab Syntax
S = SVD (X) [U, S, V] = SVD (X) [U, S, V] = SVD (X, 0)
The c prototype for mlfsvd () is constructed step-by-step. Until the last step, the prototype is incomplete.
Adding the Output Arguments
1- Find The Statement That Includes The Largest Number of Output Arguments.choose:
[U, S, V] = SVD (X, 0) 2- Subtract Out The First Output Argument, U, TO BE The Return Value from The Function. The Data Type for the return value is mxArray *.
MxArray * mlfsvd (
3- Add the remaining number of matlab output arguments, s and v, as the first, second, etc. Arguments to the c function. The data type for a c output argument is mxarray **.
MxArray * mlfsvd (mxaRray ** s, mxaRray ** V
Adding the input arguments
1- Find the syntax what incruDes the largest number of infut arguments.com.com:
[U, s, v] = svd (x, 0)
2- Add That Number of Input Arguments, X and Zero, To The Prototype, ONE ANOTHER FOLLOWING The OUTPUT Arguments. The Data Type for an input Argument is mxarray *.
MxArray * mlfsvd (mxarray ** s, mxaRray ** v, mxaRray * x, mxaRray * zero);
The Prototype is Complete.
How To Translate A Matlab Call Into A C Call
This procedure demonstrates how to translate the MATLAB svd () calls into MATLAB C Math Library calls to mlfSvd (). The procedure applies to library functions in general.Note that within a call to a MATLAB C Math Library function, an output argument is preceded By &, An Input Argument is not.matlab syntax:
S = SVD (X) [U, S, V] = SVD (X) [U, S, V] = SVD (X, 0)
The MATLAB arguments to svd () fall into these categories: U (or s) is a required output argument.S and V are optional output arguments.X is a required input argument.Zero is an optional input argument.
1- Declare input, output, and return variables as mxArray * variables, and assign values to the input variables.2- Make the first output argument the return value from the function.s = U = U = 3- Pass any additional required or optional output arguments as the first arguments to the function. Pass a NULL argument wherever an optional output argument does not apply to the particular call.s = mlfSvd (NULL, NULL, U = mlfSvd (& S, & V, U = mlfSvd (& S, & V,
4- Pass Any Required or OPTIONAL INPUT ARGUMENTS That Apply To the C Function, Following The Output Arguments. Pass A Null Argument Does Not Apply To The Particular Call.
S = MLFSVD (NULL, NULL, X, NULL); U = MLFSVD (& S, & V, X, NULL); u = mlfsvd (& S, & V, X, ZERO);
Mathematical Functions
Every Mathematical Functions Are Begin with mlf prefix. Mlf is an abbreviation for matlab function. Below is a list of useful mathematical functions:
Mlfplus, MLFminus
MLFMTIMES, MLFMPower
Mlfacos, mlfasin
MLFCONV
MLFCONJ
Mlfdec2bin, mlfdec2hex
MLFDISP
MLFFT, MLFFFT2
MLFLINSPACE
MLFMAX, MLFMIN
MLFROOTS
mlfrot90
For Example, Conv Statement In Matlab Will Become MLFCONV IN C.
Utility functions
We use Utility Functions for Some Tasks Like Printing Content of a Matrix OR Saving / Loading Data TO / from A File. Every Utility Functions Are Begin with MX Prefix. Below Is A List of Some Utility Functions:
MXCalloc, MXFree
Mxcreatedoublematrix
MxcreateNumericArray
MxcreateString
Mxgetpi, MxGetpr
MXMalloc, MXREAlloc
Mxgetdata, MxSetData
MXDESTROYARRAY
USING C MATH LIBRARY
To Add Support of Matlab C Math Library Follow Thase Instructions: 1- Add Following Line At The end of stdafx.h
#include
2- Add Desired Libraries to your Project (in this example, libmat.lib, libmx.lib, libmatlbmx.lib and libmatlb.lib)
3- Compile your project!
Sample Program
#include "stdafx.h"
Int main (int Argc, char * argv [])
{
Double dblarray [] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; mxaRray * a, * b
A = MXCREATEDOUBLEMATRIX (3, 3, MXREAL);
// Copy Array to Matrix A
Memcpy (mxgetpr (a), dblarray, 9 * sizeof (double));
A = MLFMTIMES (A, A); //a=a. 1;
MLFPRINTMATRIX (A);
// CREATING MAGIC MATRIX
B = mlfmagic (mlfscalar (3)); // Magic Matrix of Order 3 mlfprintmatrix (b); MXDESTROYARRAY (A); MXDESTROYARRAY (B);
Return 0;
}
Requirements
1- Matlab V5.0 or Higher
2- Matlab C Math Library Toolbox
3- Knowledge of Matlab Programming!
References
1-Matlab C Math Library (MathWorks)
2- C Math Library Reference (MathWorks)
Enjoy!