Jump to content

memory mapped file questions


Recommended Posts

hi guys  i have  in  c#  a code for memory mapped file (without file )

using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;

class Program
{
    // Process B:
    static void Main(string[] args)
    {
        try
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("Test"))
            {

                Mutex mutex = Mutex.OpenExisting("testmapmutex");
                mutex.WaitOne();

                using (MemoryMappedViewStream stream = mmf.CreateViewStream(1, 0))
                {
                    BinaryWriter writer = new BinaryWriter(stream);
                    writer.Write("0");
                }
                mutex.ReleaseMutex();
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Memory-mapped file does not exist. Run Process A first.");
        }
    }
}

exist a mode  for read  by Autoit  ??

or  exist some documentation i find only this  but  is  old  and  give me rror in dll

thankz  at all

 

Link to comment
Share on other sites

o thankz  i try to catch  a memory mapped  file  C# , in autoit    build  this  simple  code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.MemoryMappedFiles;

namespace csharpmapmem1
{
    class Program
    {
        static void Main()
        {
            byte[] Buffer = ASCIIEncoding.ASCII.GetBytes("35;2020.06.26 10.00.01;ASK;1,12445;1");
            MemoryMappedFile mmf = MemoryMappedFile.CreateNew("Test", 1000);
            MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
            accessor.Write(54, (ushort)Buffer.Length);
            accessor.WriteArray(54 + 2, Buffer, 0, Buffer.Length);
            Console.WriteLine("Memory mapped file created");
            Console.ReadLine();
            accessor.Dispose();
            mmf.Dispose();                
        }
    }
}

for  Autoit

#NoTrayIcon

#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <WinAPIHObj.au3>

Opt('WinWaitDelay', 0)

 _Receiver()


Func _Receiver()
    Local $hMapping = _WinAPI_OpenFileMapping('Test')
    If Not $hMapping Then Return

    Local $pAddress = _WinAPI_MapViewOfFile($hMapping)
    Local $tData = DllStructCreate('USHORT[1000]', $pAddress)
    Local $sText

        Sleep(2000)
        $sText = DllStructGetData($tData, 1)
        DllStructSetData($tData, 1, '')
        If $sText Then MsgBox(BitOR($MB_ICONINFORMATION, $MB_SYSTEMMODAL),   " (receiver)", "                                               " & @CRLF & $sText)

    _WinAPI_UnmapViewOfFile($pAddress)
    _WinAPI_CloseHandle($hMapping)
EndFunc   ;==>_Receiver

i  run   the  first C# code  and  after run a  autoit code  , but  not  appear nothing  and  not return error

whats  wrong ???

thankz at all

Link to comment
Share on other sites

Hello. 

Just Make sure to review your code deeply.

 

#NoTrayIcon

#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <WinAPIHObj.au3>

Opt('WinWaitDelay', 0)

_Receiver()


Func _Receiver()
    Local $hMapping = _WinAPI_OpenFileMapping('Test')
    If Not $hMapping Then Return

    Local $pAddress = _WinAPI_MapViewOfFile($hMapping)
    Local $tData = DllStructCreate('byte[1000]', $pAddress)
    Sleep(2000)
    Local $bText = DllStructGetData($tData, 1) ;Get Text in Binary
    Local $tStr = DllStructCreate("char Str[100]", $pAddress + 56) ;Address+Offset where you write from C# //accessor.WriteArray(54 + 2, Buffer, 0, Buffer.Length);
    If $bText Then MsgBox(BitOR($MB_ICONINFORMATION, $MB_SYSTEMMODAL), "Show Binary (receiver)",  $bText)
    If $tStr.Str Then MsgBox(BitOR($MB_ICONINFORMATION, $MB_SYSTEMMODAL), "Show Text (receiver)", $tStr.Str)

    _WinAPI_UnmapViewOfFile($pAddress)
    _WinAPI_CloseHandle($hMapping)
EndFunc   ;==>_Receiver

 

Saludos

Link to comment
Share on other sites

Couple of small issues  I  foresee:

1-  Sender needs to close handle when file map is not required anymore 

2-  Receiver should erase content of the file map after reading so sender knows that content has been well received

Link to comment
Share on other sites

2 hours ago, Danyfirex said:

Local $tData = DllStructCreate('byte[1000]', $pAddress)

why you use here  byte ?

and why you use ?

2 hours ago, Danyfirex said:

"char Str[100]

 

43 minutes ago, Nine said:

Couple of small issues  I  foresee:

1-  Sender needs to close handle when file map is not required anymore 

2-  Receiver should erase content of the file map after reading so sender knows that content has been well received

yes  of course  , but  first  i must  understund  how work memory mapp.

the  finel plan is  program A  in c#  put out  a tream of data continuosly , and  my program in Autoit  read them  in realtime and  do somthing

but a  step at time :) thankz at all

 

Link to comment
Share on other sites

3 minutes ago, faustf said:

why you use here  byte ?

and why you use ?

Because if you do not use byte or char or wchar, you will get only the first element of the array structure and not all the content of the array.

Link to comment
Share on other sites

questions  i try to understund i   insert a  mem file in this scritp in c#

#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
using System.IO;
using System.IO.MemoryMappedFiles;
#endregion

//This namespace holds Indicators in this folder and is required. Do not change it. 
namespace NinjaTrader.NinjaScript.Indicators
{
    public class Aziocane : Indicator
    {
        MemoryMappedFile    file;
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description                                 = @"Enter the description for your new custom Indicator here.";
                Name                                        = "Aziocane";
                Calculate                                   = Calculate.OnBarClose;
                IsOverlay                                   = false;
                DisplayInDataBox                            = true;
                DrawOnPricePanel                            = true;
                DrawHorizontalGridLines                     = true;
                DrawVerticalGridLines                       = true;
                PaintPriceMarkers                           = true;
                ScaleJustification                          = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                //Disable this property if your indicator requires custom values that cumulate with each new market data event. 
                //See Help Guide for additional information.
                IsSuspendedWhileInactive                    = true;
            }
            else if (State == State.Configure)
            {
                    file    = MemoryMappedFile.CreateOrOpen("Test", 1000,  MemoryMappedFileAccess.ReadWrite);
            }
            else if (State == State.Terminated)
            {
                file.Dispose();
            }
        }

        protected override void OnBarUpdate()
        {
            //Add your custom indicator logic here.
            byte[] data = Encoding.UTF8.GetBytes ("This is a test vvvvvvvvvvvvv");
             
            
                using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                {
                    accessor.Write(0,data.Length);
             
                }
        }
    }
}

and try to catch with this script in autoit but  return me all zero Show Binary (receiver) 0x1c000.... and not return text

#NoTrayIcon

#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <WinAPIHObj.au3>
#include <WinAPIError.au3>


Opt('WinWaitDelay', 0)

_Receiver()


Func _Receiver()
    Local $hMapping = _WinAPI_OpenFileMapping('Test')
    If $hMapping = 0 Then
        MsgBox(0, '', _WinAPI_GetLastErrorMessage())
    EndIf
    If Not $hMapping Then Return

    Local $pAddress = _WinAPI_MapViewOfFile($hMapping)
    ;ConsoleWrite("Demade " & $pAddress & @CRLF)
    Local $tData = DllStructCreate('byte[1000]', $pAddress)
    Sleep(2000)
    Local $bText = DllStructGetData($tData, 1) ;Get Text in Binary
    Local $tStr = DllStructCreate("char Str[100]", $pAddress + 56) ;Address+Offset where you write from C# //accessor.WriteArray(54 + 2, Buffer, 0, Buffer.Length);
    If $bText Then MsgBox(BitOR($MB_ICONINFORMATION, $MB_SYSTEMMODAL), "Show Binary (receiver)", $bText)
    If $tStr.Str Then MsgBox(BitOR($MB_ICONINFORMATION, $MB_SYSTEMMODAL), "Show Text (receiver)", $tStr.Str)

    _WinAPI_UnmapViewOfFile($pAddress)
    _WinAPI_CloseHandle($hMapping)
EndFunc   ;==>_Receiver

whats wrong ?

Link to comment
Share on other sites

  protected override void OnBarUpdate()
        {

when the  bar is  update  do it

  byte[] data = Encoding.UTF8.GetBytes ("This is a test vvvvvvvvvvvvv");
             
            
                using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                {
                    accessor.Write(0,data.Length);
             
                }

 

when  attach the indicator  over the chart ( only one time )

else if (State == State.Configure)
            {
                    file    = MemoryMappedFile.CreateOrOpen("Test", 1000,  MemoryMappedFileAccess.ReadWrite);
            }
         

when  remove  the indicator over chart (only one time )

  else if (State == State.Terminated)
            {
                file.Dispose();
            }

therfore  i  suppose  when barupdate rewrite  the file  like a stream , i suppose , but problably not understund  good

 

Link to comment
Share on other sites

$pAddress is a pointer in receiver (= file mapping successful)?

Try StringToBinary($bText) instead of the new structure. > Edit: BinaryToString($bText) of course 🤐

Edited by KaFu
Link to comment
Share on other sites

8 minutes ago, KaFu said:

Try StringToBinary($bText) instead of the new structure.

but  with this

Local $bText = DllStructGetData($tData, 1) ;Get Text in Binary

convert  text in binary  why i must convert again ??

or  you intend somthing like this ?

    Local $bText = StringToBinary($tData) ;Get Text in Binary

 

Link to comment
Share on other sites

i tryed also in this mode  but nothing :(

namespace NinjaTrader.NinjaScript.Indicators
{
    public class Aziocane : Indicator
    {
        MemoryMappedFile    file;
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description                                 = @"Enter the description for your new custom Indicator here.";
                Name                                        = "Aziocane";
                Calculate                                   = Calculate.OnBarClose;
                IsOverlay                                   = false;
                DisplayInDataBox                            = true;
                DrawOnPricePanel                            = true;
                DrawHorizontalGridLines                     = true;
                DrawVerticalGridLines                       = true;
                PaintPriceMarkers                           = true;
                ScaleJustification                          = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                //Disable this property if your indicator requires custom values that cumulate with each new market data event. 
                //See Help Guide for additional information.
                IsSuspendedWhileInactive                    = true;
            }
            else if (State == State.Configure)
            {
                MemoryMappedFile    file    = MemoryMappedFile.CreateNew("Test", 1000);
                
            }
            else if (State == State.Terminated)
            {
                file.Dispose();
            }
        }

        protected override void OnBarUpdate()
        {
            //Add your custom indicator logic here.
            byte[] data = Encoding.UTF8.GetBytes ("This is a test vvvvvvvvvvvvv");
              MemoryMappedViewAccessor accessor = file.CreateViewAccessor();
              accessor.Write(54, (ushort)data.Length);
              accessor.WriteArray(54 + 2, data, 0, data.Length);
        }
    }
}

 

Link to comment
Share on other sites

in this mode  work (for the moment ) , thankz at all

namespace NinjaTrader.NinjaScript.Indicators
{
    public class Aziocane : Indicator
    {
        MemoryMappedFile    file;
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description                                 = @"Enter the description for your new custom Indicator here.";
                Name                                        = "Aziocane";
                Calculate                                   = Calculate.OnBarClose;
                IsOverlay                                   = false;
                DisplayInDataBox                            = true;
                DrawOnPricePanel                            = true;
                DrawHorizontalGridLines                     = true;
                DrawVerticalGridLines                       = true;
                PaintPriceMarkers                           = true;
                ScaleJustification                          = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                //Disable this property if your indicator requires custom values that cumulate with each new market data event. 
                //See Help Guide for additional information.
                IsSuspendedWhileInactive                    = true;
            }
            else if (State == State.Configure)
            {
         file   = MemoryMappedFile.CreateOrOpen("Test", 1000,  MemoryMappedFileAccess.ReadWrite);

            }
            else if (State == State.Terminated)
            {
                file.Dispose();
            }
        }

        protected override void OnBarUpdate()
        {
            //Add your custom indicator logic here.
              byte[] data = ASCIIEncoding.ASCII.GetBytes("35;2020.06.26 10.00.01;ASK;1,12445;1");
              MemoryMappedViewAccessor accessor = file.CreateViewAccessor();
              accessor.Write(54, (ushort)data.Length);
              accessor.WriteArray(54 + 2, data, 0, data.Length);
            
        }
    }
}

 

Link to comment
Share on other sites

  • 3 weeks later...

hi guys  if  someone  can help me  , my script not  work in windows 10 , but  work in win 7 , so the  script  not return error but  retun i think only offset , but not a ascii text

0_o

my code

#NoTrayIcon

#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <WinAPIHObj.au3>
#include <WinAPIError.au3>


Opt('WinWaitDelay', 0)
 while 1
_Receiver()

WEnd

Func _Receiver()
    Local $hMapping = _WinAPI_OpenFileMapping('Test')
    If $hMapping = 0 Then
        MsgBox(0, '', _WinAPI_GetLastErrorMessage())
    EndIf
    If Not $hMapping Then Return
    Local $pAddress = _WinAPI_MapViewOfFile($hMapping)
    ;ConsoleWrite("Demade " & $pAddress & @CRLF)
    Local $tData = DllStructCreate('byte[1000]', $pAddress)
    ;Sleep(2000)
    Local $bText = DllStructGetData($tData, 1) ;Get Text in Binary
    Local $tStr = DllStructCreate("char Str[100]", $pAddress + 56) ;Address+Offset where you write from C# //accessor.WriteArray(54 + 2, Buffer, 0, Buffer.Length);
    ;If $bText Then MsgBox(BitOR($MB_ICONINFORMATION, $MB_SYSTEMMODAL), "Show Binary (receiver)", $bText)
    If $tStr.Str Then ConsoleWrite ( $tStr.Str & @CRLF)

    _WinAPI_UnmapViewOfFile($pAddress)
    _WinAPI_CloseHandle($hMapping)
EndFunc   ;==>_Receiver

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...