Discussion on Delphi and MATLAB Data Interface Solution

zhaozj2021-02-16  66

Source: http://www.delphibbs.com/keylife/iblog_show.asp? XID = 2109

Overview: This article describes how to use Delphi's flexible and convenient programming capability and MATLAB powerful scientific computing power, reduce the difficulty and time to write complex algorithms, so that the development efficiency of the Delphi algorithm process is greatly improved, and it has received a half-time effect. Keywords: MATLAB, scientific calculation, interface, data exchange introduction: Recently engaged in digital image encryption topics, which involve a large number of matrices and other scientific operations, when implementing Delphi, can imagine when writing algorithms A large number of problems, so I would like to put aim to handle the background arithmetic module through a certain interface to handle other mature scientific computing software, and use Delphi engaged in its front desk development, which will greatly reduce the difficulty of writing complex algorithms. And shorten the development cycle. I believe this is also the problem that the majority of developers urgently have to wait in a large number of scientific calculations. In the forum, I have repeatedly asked, the author refers to the large amount of information, summarizes several programs, I hope to benefit everyone ^ _ ^ Delphi MATLAB Data Interface Scheme Example: Delphi as a function of powerful programming tool, has the advantages of easy-to-use, high development efficiency, beautiful interface makeup, so it is favored by many programmers. As the first structured advanced language in history, Pascal also has many advantages in the preparation of complex algorithms, but today, today's fast operation, use PASCAL originally developed some complex algorithms, not only compiling efficiency is not high and also affects Development progress, so Delphi combines the scientific computing software, and efficiently completing programming tasks into a problem that plagues many programmers. MATLAB is a highly efficient scientific engineering calculation language, which is difficult to compare advantage over other languages ​​in matrix operation, numerical calculation, digital signal processing, system identification, automatic control, neural network, graphic display. Combine Delphi and Matlab, using Delphi's flexible and convenient programming capability, MATLAB powerful scientific computing power can develop powerful and flexible software. The following gives the 5 types of data interface scenarios for your reference: (For the convenience of everyone browsing, several scenarios are displayed) Scheme One Data Transfer Method Deliver Delphi and Matlab Communication ............. ............................................. ............................................................................ ......................................... 4 floor plan four use dynamic link The library technology is implemented .......................................... .5 floors five use MIDEVA to compile the dynamic link library from the MATLAB environment (Note: This method author has not been successful) ......... 6th floor

2003-8-18 21:21:00

View reviews???

2003-8-18 21:22:54

Solution A Data Transfer Method for Delphi and MATLAB AC. Many ways to enter data. There are many ways to enter data. Among them, use M files, directly introducing data in a MATLAB work memory method, not only syntax, but only enter files Name, MATLAB will automatically execute the statement in the M file in order; there are many ways to make MATLAB data output, in order to facilitate access to the Delphi application interface, we can use MATLAB's instruction Save output data. If the instruction save outfile.dat x y -ASCII-Double can store the variable x and y in the 16-bit ASCII code form in the 16-bit ASCII code. Based on the above MATLAB data input, output, we can use M files to transit, implement Delphi and Matlab data exchange, as you should pay attention to the following: (1) Due to MATLAB's basic data unit is a matrix, in Delphi application In the program, we only output the data to the M text file through the file variable, to create and save matrix data. (2) Since the Delphi application is running at the front desk, MATLAB.EXE can be executed in the application to call the Windows function WINEXEC. (3) Due to the M file, only in the MATLAB integration environment can be identified and automated, and according to the background requirements cannot be displayed into the MATLAB integration environment, consider the MATLAB environment variable is defined by the MATLABRC.M file, so we can pass Matlabrc.m file modification (to calculate, calculate, output data, and write into M files, add MATLABRC.M), enable MATLAB's background operation. Second, how Delphi passes the data to MATLAB This example shows more intuitive ^ _ ^ Example: Make matrix operation (b '* b) -1 * b' * y ', where B is T * 2 matrix, Y is 1 * T matrix. In the Delphi application, the following blocks can be used to participate in the matrix B, Y, Y, which can be used as M file so that MATLAB can obtain the matrix B, Y. The application segment is as follows: (FB, fb, fy is the file variable defined in advance, B [i, j], y [i] is a pre-defined array variable; 'C: / MatlabFile / Delphioutb. M 'is the M file path and file name of the matrix B,' c: /matlabfile/delphiouty.m 'is the M file path and file name of the save matrix Y) ******** Create a save matrix B M file ******** // Note: The entire luminous matrix in matlab must be "[]" to the first tail, the row of the matrix must be sequentially ";" or the parking space Isolation, matrix elements must be separated by commas "," or spaces.

Assign (FB, 'C: /matlabfile/delphiutb.m'); ReWrite (FB); Write (FB, 'B ['); for i: = 0 to T-2 Do for J: = 0 to 1 do begin Write (FB, B [IMK]); IF J <1 Then Write (FB, ',') ELSE IF (i

Copyfile ('c: /dsm/matlabfile/mymatlabrc.m', 'c: /matlab/toolbox/local/matlabrc.m', false); WINEXEC (' c: /matlab/bin/matlab.exe' ,sw_minimize) 5. How to accept the matLab output results MATLAB outputs the calculation result via Save C: /MATLABFILE/MATLABOUTFILE.DAT M -ASCII-Double, so we can get the calculation result by the following program, and put the result via the double type variable MID In-input group a [i]: (faxTfle Type Variable) IF FileExists ('c: /matlabfile/matlaboutfile.dat') Then AssignFile (fa, 'c: /matlabfile/matlaboutfile.dat'); Reset (FA) i: = 0; While Not Eof (FA) DO Begin Read (Fa, MID); A [I]: = MID; i: = i 1; End; CloseFile (FA); additionally, completion of the above steps After the interface, you will need to add the following code to the application to restore the MATLAB original environment parameter setting: CopyFile ('c: /matlabfile/matlabrcbak.m', 'c: /matlab/toolbox/local/matlabrc.m', False); However, due to the use of data transfer, the running speed is greatly affected when there is a large amount of data. 2003-8-18 21:23:57

Solution 2 Dynamic Data Switching 1. The basic idea scheme needs to perform both data transfer in the form of file, then there is a solution that is directly delivered, the answer is certain. We know that DDE is a messaging mechanism based on Windows, which is "dialog" between client and server programs, which allows real-time data exchange between two or more applications. According to this, we can use DDE to implement Delphi and Matlab data transfer. Second, the part of the DDE Application Protocol DDE is called a client program, and the part of the response is called a server program (Server). The DDE server is responsible for maintaining the data used by other Windows programs, while the DDE client is responsible for obtaining data from the server. Dynamic Data Exchange between applications must comply with DDE protocols, and DDE protocols mainly have three layers, applications, conversational, Topic, and dialog project layers (Items), and definitions of each layer are: 1 application The Application Application layer is mainly channel of the conversation, and the DDE dialog is usually caused by the client, including initialization related parameters, ready to start dialogue. 2 Dialog Theme Layer (Topic) Dialog Theme is the data unit that the DDE server can identify, is usually a file name, the form name, can also be the name of the ServerConv component in Delph, two main themes: 2: SYSTEM and ENGINE, see Table 1. 3 Dialog Project Layers (Item) dialog project layer is used to determine content for dynamic data exchange, such as sending data, accept data, or cells in the table, etc. In the application in Delphi, the name of the DDeServerItem component. Two topics in Matlab include Systems, Format, Topics, EngevalString, EngsringResult, Engfigureresult, etc., in Table 1, you can view details. Both Madab and Delphi support DDE technology, which can be used as a client program.

It can also be used as a server program. Here we only use Delph as a client program, MATLAB is discussed as a server program, and the Delphi client is dialogue with the DDE component provided by the DDE component to complete the dynamic exchange of data. Third, Delphi DDE Component Table 1 Matlab DDE Server Composition System Subject Project: Function: Systems Contains All Item List Supported by System Topics Format Contains All Data Formats Supported by MATLAB DDE Server Topics contains Matlab DDE Server All of the topic names of thermally supported ENGINE Topic Items: Functions: ENGEVALSTRING Send Commands to the MATLAB Server Execute ENGSTRINGRESULT Data from the MATLAB Server ENGFIGURESULT ENGFIGURESULT from the MATLAB server Request to get a graphic format data from the MATLAB server The request acquisition matrix data Delphi provides four components for DDE: DDECLICNTCONV, DDECLIENLITEM, DDeServerConv, and DDeServerConv, where the first two are used as the client, and then two are used as a server program. When using Delphi as a customer program, DDECLIENTCONV and DDECLIENTITEM components must be used, and DDECLIENTCONV is used to establish a conversation and establish a dialog on the client. Important properties and methods include ConnectMode, DDService, Ddetopic, SetLink, Pokedata. ExecuteMacro et al: DDECLIEntItem is used for client registration dialog projects with DDECONV, DDELTEM, LINES, and the server is closely related to the server program, and data returned from the server is often in this component. Lines properties. The specific usage and definition can be found from the Delphi Help file. 4. When the MATLAB DDE server is accessible as a server, the MATLAB must provide the name, theme, and project of the server. In the Win32 system, MATLAB's DDE server is named Matlab, supports two conversational topics: System and Engine, with several items below each topic, through them can complete different tasks. The corresponding function can be checked from the table one. When Madab acts as a server, supports three data transfer formats: text format, meta-file diagram, XLTALLLE, which is used to store character rate data format ending at empty characters. The metafile diagram is used to store graphical data format, and XLTable is a special data format that supports Excel. V. DDE implementation of Delphi and Matlab DDE technology is already a very mature Windows process communication mechanism, DVHI and MATLAB Dynamic Data Exchange We use Delphi as a client, MATLAB is used as a server.

First start the Delphi client, establish a dialog theme, and then connect to the MATLAB server and establish DDE dialog. In Delphi, two ways to connect with the server are automatic and manual, and can be set via the ConnectMode property of the DECLIENTCONV component. The former must call the OpenLink method for the DDECLIENTCONV component to establish a DDE dialog, and the latter can automatically establish a conversation when connecting. Establish a dialog theme and establish a conversation, you can implement dynamic exchange of different data between Delphi and Matlab, send commands and data to the MATLAB server, including graphic data and text data to the server, including graphical data and text data, including graphics data and text data, including graphics data, and text data, send commands and data to the MATLAB server. Wait. 6. Summary of program summary Data transfer directly between Matlab and Delphi, improve the speed of operation, but steps are more annoying, sometimes inexplicably wrong --_- b2003-8-18 21:24:29

Solution 3 creates an ActiveX object to implement data exchange 1. Basic ideas ActiveX is a component integration protocol established by Microsoft, which is not limited by the development environment. ActiveX controls can be used in different environments, including Delphi, C Builder, VC , VB, and Internet Explore. Both MATLAB and DELPHI support ActiveX technology, so ActiveX automation servers and automation controller technology can be utilized to implement Matlab and Delphi interfaces. Second, MATLAB Automation Server Automation Server is a component that can be driven by other applications, whose core is to include one or more IDSPATCH-based interfaces for other programs created and connected. When MATLAB is used as an automated server, it can be used by any application as an automation controller on the Windows platform. MATLAB ActiveX Objects Defined in the System Registry (Progid) is matLab.Application.5 or Matlab.Application.single. When you create a MATLAB Automation Server with MATLAB.Application.5, the system will no longer be initialized, but all the arguments are completed as a shared server. When using matLab.Application.single, the MATLAB Automation Server will be used as a separate server without sharing with other programs. For the use of MATLAB automation servers, the system provides five ways: Excute, PutfullMatrix, GetFullMatrix, MinimizeCommandWindow, MaximizeCommandWindow. Among them, Excute is used to perform matlab commands, PUTFULLMATRIX and GETFULLMATRIX for data delivery, MinimizeCommandWindows for interface window coal. Three, Delphi Delphi5 automation controller provides two functions for the ActiveX programming interfaces and objects: GetActiveOleObject and CreateOleObject, the format: function GetActiveOleObject (const ClassName: string): IDispatch; function CreateOleObject (const ClassName: string): IDispatch; wherein GetActiveoleObject is used to access the currently running ActiveX object table, returns the specified ActiveX object; createoleObject is used to create a specified, Song initialization ActiveX object. You can create an object instance of a MATLAB automation server by calling these two functions. Fourth, an example program gives a specific example to illustrate the automation of MATLAB in Delphi using ActiveX. First add USES COMOBJ in Unit's Uses statement.

And add the following statement: procedure TForm1.Button1Click (Sender: Tobject); var matlab: variant; begin try matlab: = GetActiveOleObject ( 'Matlab.Application'); except matlab: = CreateOleObject ( 'Matlab.Application'); matlab: = CreateoleObject ('matlab.application.5'); matlab.execute ('a = [1 2 3 4 5 6 7 8];'); MATLAB.EXECUTE ('b = [2 3 4 4 5 6 2 2]' ); MATLAB.EXECUTE ('Plot (a, b)'); End end; 5, the program summary This scheme uses a more common ActiveX method under Win32 program to perform data exchange, and it is easy to implement. However, it is necessary to pay attention, when the program is running, it will cost a MATLAB window when you create an object, and it will generate a MATLAB window (this is very uncomfortable!). The author also encountered a problem, I don't know if it is a special case, that is, the same image data running under Matlab and the results after running through Delphi are sometimes a bit different. For example, I am now engaged in image encryption, in two The image quality after environmental encryption is different (the algorithm is the same), inexplicable ... 2003-8-18 21:25:18

Program 4 uses dynamic link library technology to communicate. First, the basic ideas MATLAB does not provide the Delphi application interface, but provides a Win32 platform VC application interface, including the MATLAB engine, C / C function library . You can use the MATLAB and VC interface functions, and the Data transfer is performed by the MATLAB engine, and the Dynamic connection library of the C language is written as a MATLAB and Delphi interface, and then the C dynamic library function is called in Delphi. The C language call function of the MATLAB engine is shown in Table 1. Table 1: The C language call function function function name function of the MATLAB engine engevalstring Opens the MATLAB Engine EngevalString In the MATLAB Engine ENGPUTARRAY Put the data into the MATLAB Engine ENGGETARRAY Remove the data in the MATLAB engine. ENGCLOSE is turned off. When the MATLAB engine function is used, you want to use the MATLAB array (MxArray), the MATLAB engine uses this data type to make a variety of data processing work. Various variables in MATLAB, including scales, vectors, matrices, strings, etc., are all stored in this MATLAB array. MATLAB provides the format of the MATLAB array (MxArray) in the C language to define its data structure. There is no corresponding MATLAB array under Delphi, but the dynamic connection library can be used to solve this problem. Second, the design of the dynamic connection library In our design software, you should send data in Delphi to MATLAB, select the appropriate handler, and then send the result back to Delphi. In order to achieve the above object, the corresponding several functions are designed. These functions are placed in the DPLAB.DLL dynamic connection library. The basic composition of DPLAB.DLL is as follows: (1) Head function #include "stdafx.h" #include #include #include #include "engine.h" //// Under Matlab / Extern / Include, copy it to the current directory Engine * EP = NULL; // MATLAB engine, global variable MxArray * PA = NULL; // Matlab array pointer. Multiple MXARRAY pointer variables (2) can be defined as needed to open the MATLAB engine function: EXTERN "C" declspec (DLLEXPORT) INT Matopeneng (FAR Char * CC) {if (EP) Return 0; // Exit IF if it is opened ! (EP = EngOpen (CC))) Return -1; Else Return 1;} If matlab is installed on the local computer, the content in the string CC is "/ 0", if the system is a client / server (Client / Server ) Work mode, Matlab is installed on the host "Host", you can enter '// Host / Matlib'.

(3) Close the function of the MATLAB engine Extern "C" DECLSPEC (DLLEXPORT) INT MATCLOSEENG (VOID) {if (EP) {IF (PA) MXDESTROYARRAY (PA); // Release Pa ENGCLOSE (EP); EP = NULL; RETURN1 Else Return0;} (4) Execute the MATLAB command function: Extern "C" declspec (DLLEXPORT) INT MATEXEC (FAR Char * CC) {if (! EP) Return0; ENGEVALSTRING (EP, CC); // CC Matlab Command Return 1;} (5) Creating MxArray variables based on known data: // Note: CC: MATLAB variable name NUM: Data DD: Known Data EXTERN "C" DECLSPEC (DLLEXPORT) INT Matcreatedoubled (char * CC, INT NUM, DOUBLE DD []) {if (! EP) RETURN 0; IF (Num <1) Return -1; PA = MXCreatedoublematrix (1, Num, MXREAL); MXSetName (Pa, FH [Getfh (CC) ]); // Specify the variable name in matlab, it must be a static string! Memcpy (Char *) MxgetPR (Pa), (char *) DD, Num * SizeOf (Double)); ENGPUTARRAY (EP, PA); Return1;} (6) Get MATLAB data: // Note: CC: MATLAB variable name NUM: Data number DD: Return Data EXTERN "C" DECLSPEC (DLLEXPORT) Int matGetDoubledata (char * cc, int number, double dd " ]) {MxArray Result; INT i; if (! EP) RETURN0; IF (Num <1) Return-1; Result = ENGTARRAY (EP, FH [Get FH (CC)]); if (Result) {PDATA = (double) mxgetdata (result); for (i = 0; i

Third, various functions use 1 in Delphi 1. In order to use dynamic connection functions in Delphi, you must first declare these functions: function matopeneng (p: pchar): integer; stdcall; external'dPlab.dll '; function MatCloseEng: Integer; stdcall; external'DpLab.dll '; function MatExec (p: PChar): Integer; stdcall; external'DpLab.dll'; function MatCreateDoubleD (p: Pointer; num: Integer; dd: Array of double) : Integer; stdcall; external'DPLAB DLL '; Function Matgetdoubledata (P: Pointer; Num: Integer; Dd: array of double): integer; stdcall; external'DPLAB DLL'; functions declare, you can easily use them . Open the MATLAB engine: matopeneng (PCHAR (/ 0 ')); Turn off the MATLAB engine: matcloseng; 2, the following program gives the method of obtaining data from MATLAB, the function MatgetdoubleData specifies the data variable name in MATLAB via the variable cc This variable should be defined: procedure tform1button2click (sender: TOBJECT); var Dd: array [0..10] of double; cc: char; i: integer; begin cc: = 'd'; // matlab The variable name Matgetdoubledata (@ CC, 10, DD); listbox1.clear; // Display the read data for i: = 0 to 4 do listbox1.items.add (Format ('%. 2f) in a list box. , [DD [I]])); END; 3, below gives Delphi to draw a three-dimensional graphic program with SIN (R) / R function in matlab, the rest of the case, you touch the class, ^ _ ^ Procedure TFORM1BUTTON3CLICK (Sender: TOBJECT Begin Matexec (PCHAR ('x = -8: 5: 8;')); MATEXEC (PCHAR ('y = x', ';'); Matexec (Pchar ('x = "(size (y) ) * x; ')); MATEXEC (PCHAR (' y = y * one "; MATEXEC (PCHAR ('R = SQRT (x. ^ 2 Y. ^ 2) EPS ; ')); MATEXEC (PCHAR (' z = sin (r) / r; ')); Matexec (Pchar (' Mesh (z); ')); end; four, program summary actually ideas and previous solutions Very like, the difference is to implement data transfer by calling the MATLAB application interface instruction in the DLL. The dynamic connection library provided by this scheme is actually an exemplary example. According to the actual needs, it can also develop a more powerful function. To meet the needs of different applications. It is necessary to spend a certain time to write related DLLs ^ _ ^ 2003-8-18 21:25:54

Program 5 uses MIDEVA to compile dynamic link library from MATLAB environments, basic ideas If you have seen several programs, you will find that they must rely on the MATLAB environment, so how can I completely leave the MATLAB environment? This is also my recent research, but the sky is not casual with 555555555, although the relevant information is found, but the actual situation is too far. After all, I would like to send this article after I have to get all the articles. Later, I would like to let everyone study together, maybe a certain person can refer to the mystery. This method uses a software called MIDEVA, which is a MATLAB compilation development software platform introduced by MathTools (Note: MaathTools has been acquired by MathWork), and Mediva has compiled conversion function and can make MATLAB functions The written MATLAB program is converted to a C form of DLL, then call the dynamic library function in Delphi, without having to rely on the Malab environment, premise must have two dynamic link libraries MDV4300 and AGO4300. Second, the compilation step Implementing the MIDEVA platform to implement the Delphi and M file mixed programming steps as follows: 1 If it is real, it will save a lot of unnecessary trouble, but the IP has a DLL compiled with Mideva, and Delphi cannot recognize -_- b, and it does not find MDV4300 and AGO4300 two dynamic link libraries. If the friend can succeed, I hope to tell, I am grateful. 2003-8-18 21:26:46

Postscript: Matlab and Delphi are powerful computer languages, using interface technology to make full use of Delphi efficient, convenient visualization development environment and MATLAB in terms of numerical calculation, algorithm design, etc., improve procedures development efficiency, and save a lot of money The time spent on mathematical operations can quickly develop interface-friendly algorithms and numerical analysis, data processing software. At the same time, it should be seen that all interface programs have their shortcomings, and they still have to study together. My Email, welcome everyone to discuss: Yellowfish2001@sina.com

转载请注明原文地址:https://www.9cbs.com/read-14577.html

New Post(0)