Доступ к удаляемой сборке .NET с помощью Native .NET API: Камера и Struct

Зачем использовать API .NET с массивами ячеек и структурами?

Использование представлений .NET MATLAB® struct и массивы ячеек рекомендованы, если оба из них true:

  • У вас есть функции MATLAB на сервере с типами данных struct или камера в качестве входов или выходов

  • Вы не хотите или не должны устанавливать MATLAB Runtime на свои клиентские компьютеры

Родной MWArray, MWStructArray, и MWCellArray классы являются представителями MathWorks.MATLAB.NET.Arrays.native пространство имен.

Имена классов в этом пространстве имен идентичны именам классов в MathWorks.MATLAB.NET.Arrays. Различие, что собственные представления struct и массивов ячеек не имеют методов или свойств, которые требуют MATLAB Runtime.

The matlabroot\ toolbox\dotnetbuilder\Примеры\VS Version\ NET папка имеет примеры решений, которые вы можете практиковать создание. The NativeStructCellExample папка содержит примеры собственного struct и камер.

Создание своего компонента

Этот пример демонстрирует, как развернуть удаляемый компонент с помощью собственного struct и массивов ячеек. Прежде чем настраивать удаляемый код клиента и сервера, создайте удаляемый компонент.

Если компонент, который вы хотите развернуть, еще не построен, см. инструкции в разделе Создание удаляемого компонента с помощью приложения Library Compiler или Создание удаляемого компонента с помощью команды mcc.

Пример собственных камер .NET и Struct

В серверном приложении размещен удаленный компонент.

Клиентское приложение, выполняемое в отдельном процессе, получает доступ к удаленному компоненту, размещенному в серверном приложении. Создайте сервер с помощью Microsoft® Визуальная студия® файл проекта NativeStructCellServer.csproj:

  1. Измените ссылки для сгенерированной сборки компонента на component_name\ для _ redistribution _ файлы _ only\ component_nameNative.dll.

  2. Выберите соответствующую платформу сборки.

  3. Выберите Debug или Release режим.

  4. Создайте NativeStructCellServer проект.

  5. Предоставьте файл строения для NativeStructCellServer. Код C # для сервера находится в файле NativeStructCellServer.cs:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.Remoting;
    
    namespace NativeStructCellServer
    {
      class NativeStructCellServer
         {
           static void Main(string[] args)
            {
               RemotingConfiguration.Configure(
                                 @"NativeStructCellServer.exe.config");
    
               Console.WriteLine("NativeStructCell Server started...");
    
               Console.ReadLine();
            }
         }
    }
    
    Этот код считывает связанный файл строения, чтобы определить:

    • Имя компонента, который будет размещен

    • Протокол удаленного взаимодействия и форматирование сообщений для использования

    • Время аренды удаленного компонента

    В сложение, код также сигнализирует о том, что сервер активен и ждет возврата каретки перед завершением.

Кодирование и создание клиентского приложения и файла строения

Клиентское приложение, выполняемое в отдельном процессе, получает доступ к удаленному компоненту, работающему в серверном приложении, созданном в примере Native .NET Cell и Struct. Создайте удаленный клиент с помощью файла проекта Microsoft Visual Studio NativeStructCellClient\NativeStructCellClient.csproj. Чтобы создать удаленный клиент с помощью Microsoft Visual Studio:

  1. Измените ссылки для сгенерированной сборки компонента на component_name\ для _ redistribution _ файлы _ only\ component_nameNative.dll.

  2. Измените ссылки для сгенерированной сборки интерфейса на component_name\ для _ redistribution _ файлы _ only\I component_nameNative.dll.

  3. Выберите соответствующую платформу сборки.

  4. Выберите Debug или Release режим.

  5. Создайте NativeStructCellClient проект.

  6. Предоставьте файл строения для NativeStructCellClient.

Код NativeStructCellClient

Код C # для клиента находится в файле NativeStructCellClient\NativeStructCellClient.cs:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Configuration;
using MathWorks.MATLAB.NET.Arrays.native;

using INativeStructCellCompNative;

// This is a simple example that demonstrates the use 
// of MathWorks.MATLAB.NET.Arrays.native package. 
namespace NativeStructCellClient
{
    class NativeStructCellClient
    {
        static void Main(string[] args)
        {
            try
            {
                RemotingConfiguration.Configure(
                                        @"NativeStructCellClient.exe.config");
                String urlServer = 
                    ConfigurationSettings.AppSettings["NativeStructCellServer"];
                INativeStructCellClassNative nativeStructCell = 
                    (INativeStructCellClassNative)Activator.GetObject(typeof
                                    (INativeStructCellClassNative), urlServer);

                MWCellArray field_names = new MWCellArray(1, 2);
                field_names[1, 1] = "Name";
                field_names[1, 2] = "Address"; 

                Object[] o = nativeStructCell.createEmptyStruct(1,field_names);
                MWStructArray S1 = (MWStructArray)o[0];
                Console.WriteLine("\nEVENT 2: Initialized structure as 
                             received in client applications:\n\n{0}" , S1);

                //Convert "Name" value from char[,] to a string since there's
                       no MWCharArray constructor on server that accepts
                //char[,] as input.
                char c = ((char[,])S1["Name"])[0, 0];
                S1["Name"] = c.ToString();                

                MWStructArray address = new MWStructArray(new int[] { 1, 1 }, 
                             new String[] { "Street", "City", "State", "Zip" });
                address["Street", 1] = "3, Apple Hill Drive";
                address["City",   1] = "Natick";
                address["State",  1] = "MA";
                address["Zip",    1] = "01760";

                Console.WriteLine("\nUpdating the 'Address' field to 
                                                       :\n\n{0}", address);
                Console.WriteLine("\n#################################\n");
                S1["Address",1] = address;

                Object[] o1 = nativeStructCell.updateField(1, S1, "Name");
                MWStructArray S2 = (MWStructArray)o1[0];

                Console.WriteLine("\nEVENT 5: Final structure as 
                                         received by client:\n\n{0}" , S2); 
                Console.WriteLine("\nAddress field: \n\n{0}" , S2["Address",1]);
                Console.WriteLine("\n#################################\n");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            Console.ReadLine();
        }
    }
}

Этот код делает следующее:

  • Клиент считывает связанный файл строения, чтобы получить имя и местоположение удаляемого компонента.

  • Клиент создает экземпляры удаляемого объекта с помощью статического Activator.GetObject метод

  • С этого момента удаленный клиент вызывает методы на удаляемом компоненте так же, как и локальный метод компонента.

Строение NativeStructCellClient

Файл строения для NativeStructCellClient находится в файле NativeStructCellClient\NativeStructCellClient.exe.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="NativeStructCellServer" value=
              "tcp://localhost:1236/NativeStructCellClass.remote"/>    
  </appSettings>
  <system.runtime.remoting>
    <application>
      <channels>
        <channel name="NativeStructCellChannel" ref="tcp" port="0">        
          <clientProviders>            
            <formatter ref="binary" />
          </clientProviders>
          <serverProviders>            
            <formatter ref="binary" typeFilterLevel="Full" />
          </serverProviders>            
        </channel>
      </channels>
    </application>
  </system.runtime.remoting>
</configuration>

Этот код задает:

  • Имя удаленного сервера компонентов и URI удаленного компонента (унифицированный идентификатор ресурса)

  • Протокол удаленного взаимодействия (TCP/IP) и номер порта

  • Форматтер сообщений (binary) и разрешения для канала связи (full доверие)

Запуск серверного приложения

Запустите сервер, выполнив следующие действия:

  1. Откройте DOS или UNIX® командное окно и cd на NativeStructCellServer\bin\x86\v4.0\Debug.

  2. Выполняйте NativeStructCellServer.exe. Появится следующий выход:

    EVENT 1: Initializing the structure on server and sending 
             it to client:
            Initialized empty structure:
    
          Name: ' '
       Address: []
    
    
    ##################################
    
    EVENT 3: Partially initialized structure as 
             received by server:
    
          Name: ' '
       Address: [1x1 struct]
    
    Address field as initialized from the client:
    
       Street: '3, Apple Hill Drive'
         City: 'Natick'
        State: 'MA'
          Zip: '01760'
    
    ##################################
    
    EVENT 4: Updating 'Name' field before sending the 
             structure back to the client:
    
          Name: 'The MathWorks'
       Address: [1x1 struct]
    
    
    ##################################
    

Запуск клиентского приложения

Запустите клиент, выполнив следующие действия:

  1. Откройте командное окно DOS или UNIX и cd на NativeStructCellClient\bin\x86\v4.0\Debug.

  2. Выполняйте NativeStructCellClient.exe. После инициализации MATLAB Runtime появляется следующий выход:

    EVENT 2: Initialized structure as 
             received in client applications:
    
    1x1 struct array with fields:
           Name
           Address
    
    Updating the 'Address' field to :
    
    1x1 struct array with fields:
           Street
           City
           State
           Zip
    
    #################################
    
    
    EVENT 5: Final structure as received by client:
    
    1x1 struct array with fields:
           Name
           Address
    
    Address field:
    
    1x1 struct array with fields:
           Street
           City
           State
           Zip
    
    #################################
    

Кодирование и создание клиентского приложения и файла строения с помощью собственных классов MWArray, MWStructArray и MWCellArray

createEmptyStruct.m

Инициализируйте структуру на сервере и отправьте ее клиенту со следующим кодом MATLAB:

function PartialStruct = createEmptyStruct(field_names)

fprintf('EVENT 1: Initializing the structure on server 
                         and sending it to client:\n');

PartialStruct = struct(field_names{1},' ',field_names{2},[]);

fprintf('         Initialized empty structure:\n\n');
disp(PartialStruct);
fprintf('\n##################################\n');

updateField.m

Получите частично обновленную структуру от клиента и добавьте к ней больше данных, прежде чем передать ее обратно клиенту со следующим кодом MATLAB:

function FinalStruct = updateField(st,field_name)

fprintf('\nEVENT 3: Partially initialized structure as 
                              received by server:\n\n');
disp(st);
fprintf('Address field as initialized from the client:\n\n');
disp(st.Address);
fprintf('##################################\n');

fprintf(['\nEVENT 4: Updating ''', field_name, ''' 
   field before sending the structure back to the client:\n\n']);
st.(field_name) = 'The MathWorks';
FinalStruct = st;
disp(FinalStruct);
fprintf('\n##################################\n');

NativeStructCellClient.cs

Создайте код C # клиента:

Примечание

В этом случае вам не нужна MATLAB Runtime на системном пути.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Configuration;
using MathWorks.MATLAB.NET.Arrays.native;

using INativeStructCellCompNative;

// This is a simple example that demonstrates the use of 
//     MathWorks.MATLAB.NET.Arrays.native package. 
namespace NativeStructCellClient
{
    class NativeStructCellClient
    {
        static void Main(string[] args)
        {
            try
            {
                RemotingConfiguration.Configure
                      (@"NativeStructCellClient.exe.config");
                String urlServer =
                      ConfigurationSettings.AppSettings[
                                                     "NativeStructCellServer"];
                INativeStructCellClassNative nativeStructCell = 
                      (INativeStructCellClassNative)Activator.GetObject(typeof
                           (INativeStructCellClassNative), 
                           urlServer);

                MWCellArray field_names = new MWCellArray(1, 2);
                field_names[1, 1] = "Name";
                field_names[1, 2] = "Address"; 

                Object[] o = nativeStructCell.createEmptyStruct(1,field_names);
                MWStructArray S1 = (MWStructArray)o[0];
                Console.WriteLine("\nEVENT 2: Initialized structure as received 
                                     in client applications:\n\n{0}" , S1);

                //Convert "Name" value from char[,] to a string since 
                // there's no MWCharArray constructor 
                // on server that accepts char[,] as input.
                char c = ((char[,])S1["Name"])[0, 0];
                S1["Name"] = c.ToString();                

                MWStructArray address = 
                      want new MWStructArray(new int[] { 1, 1 }, 
                             new String[] { "Street", "City", "State", "Zip" });
                address["Street", 1] = "3, Apple Hill Drive";
                address["City",   1] = "Natick";
                address["State",  1] = "MA";
                address["Zip",    1] = "01760";

                Console.WriteLine("\nUpdating the 
                                   'Address' field to :\n\n{0}", address);
                Console.WriteLine("\n#################################\n");
                S1["Address",1] = address;

                Object[] o1 = nativeStructCell.updateField(1, S1, "Name");
                MWStructArray S2 = (MWStructArray)o1[0];

                Console.WriteLine("\nEVENT 5: Final structure as received by 
                                     client:\n\n{0}" , S2); 
                Console.WriteLine("\nAddress field: \n\n{0}" , S2["Address",1]);
                Console.WriteLine("\n#################################\n");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            Console.ReadLine();
        }
    }
}

NativeStructCellServer.cs

Создайте код сервера C #:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;

namespace NativeStructCellServer
{
    class NativeStructCellServer
    {
        static void Main(string[] args)
        {
            RemotingConfiguration.Configure(
                              @"NativeStructCellServer.exe.config");

            Console.WriteLine("NativeStructCell Server started...");

            Console.ReadLine();
        }
    }
}
Для просмотра документации необходимо авторизоваться на сайте