CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2009
    Posts
    27

    IPC from c++ to c#

    Hello all,

    I am trying to create a one-way pipe from c++ to c#.
    C++ being my client sending to C# acting like my server

    So in C# I use CreateNamedPipe
    And I listen for clients to connect.

    In C++ I tried to CreateFile but this fails.
    CreateFile with pipename and open_from_existing

    Looking for some help/advice.
    Kind regards,

    C# server code :
    Code:
    class BvrServer
        {
            #region DllImports
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern SafeFileHandle CreateNamedPipe(
               String pipeName,
               uint dwOpenMode,
               uint dwPipeMode,
               uint nMaxInstances,
               uint nOutBufferSize,
               uint nInBufferSize,
               uint nDefaultTimeOut,
               IntPtr lpSecurityAttributes);
    
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern int ConnectNamedPipe(
               SafeFileHandle hNamedPipe,
               IntPtr lpOverlapped);
    
            #endregion
    
            public string pipeName = "\\\\.\\pipe\\BvrPipe";
            public Boolean running;
            public Client client;
            Thread listenThread;
            public const uint DUPLEX = (0x00000003);
            public const uint FILE_FLAG_OVERLAPPED = (0x40000000);
            public const int BUFFER_SIZE = 4096;
    
            public delegate void MessageReceivedHandler(Client client, string message);
            public event MessageReceivedHandler MessageReceived;
            
            public class Client
            {
                public SafeFileHandle handle;
                public FileStream stream;
            }
            
            public string PipeName
            {
                get { return this.pipeName; }
               
            }
    
            public bool Running
            {
                get { return this.running; }
            }
    
            public BvrServer()
            {
                this.client = new Client();
            }
    
            public void Start()
            {
                this.listenThread = new Thread(new ThreadStart(ListenForClient));
                this.listenThread.Start();
    
                this.running = true;
            }
    
            private void ListenForClient()
            {
                
                while (true)
                {
                    SafeFileHandle clientHandle =
                    CreateNamedPipe(
                         this.pipeName,
                         DUPLEX | FILE_FLAG_OVERLAPPED,
                         0,
                         255,
                         BUFFER_SIZE,
                         BUFFER_SIZE,
                         0,
                         IntPtr.Zero);
                    
                   
                    //could not create named pipe
                    if (clientHandle.IsInvalid)
                         return;
    
                    int success = ConnectNamedPipe(clientHandle, IntPtr.Zero);
                    
                    //could not connect client
                    if (success == 0)
                       return;
    
                    this.client = new Client();
                    
                    Thread readThread = new Thread(new ParameterizedThreadStart(Read));
                    readThread.Start(client);
                }
            }
                  
            private void Read(object clientObj)
            {
                Client client = (Client)clientObj;
                client.stream = new FileStream(client.handle, FileAccess.ReadWrite, BUFFER_SIZE, true);
                byte[] buffer = new byte[BUFFER_SIZE];
                ASCIIEncoding encoder = new ASCIIEncoding();
    
                while (true)
                {
                    int bytesRead = 0;
    
                    try
                    {
                        bytesRead = client.stream.Read(buffer, 0, BUFFER_SIZE);
                    }
                    catch
                    {
                        //read error has occurred
                        break;
                    }
    
                    //client has disconnected
                    if (bytesRead == 0)
                        break;
    
                    //fire message received event
                    if (this.MessageReceived != null)
                        this.MessageReceived(client, encoder.GetString(buffer, 0, bytesRead));
                }
    
                //clean up resources
                client.stream.Close();
                client.handle.Close();
                //lock (this.client);                
            }
        
        }
    C++ client code
    Code:
    void sendMessage(const char* buf){
    
        BOOL bWrite = false;
    	DWORD BYTESWRITTEN = 0;
        
        if ( pipeHandle != INVALID_HANDLE_VALUE )
    	{
    		
    		bWrite = WriteFile( pipeHandle, buf, sizeof(buf), &BYTESWRITTEN, NULL );
    		if ( bWrite == FALSE )
    		{
    			MessageBox(NULL, "WriteFile() Error!", "ERROR", MB_OK);
    		}
    	}		                        
    }  
    
    void connect(){
    
        pipeHandle =  CreateFile("\\\\.\\pipe\\BvrPipe",
                                (GENERIC_READ | GENERIC_WRITE),
                                0,
                                NULL,
                                OPEN_EXISTING,
                                0,
                                NULL);
                               
                                
        if ( !(pipeHandle != INVALID_HANDLE_VALUE ))
        {
            MessageBox(NULL, "CREATEFILE FAILED!", "ERROR!", MB_OK);   
        }
         
    }

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: IPC from c++ to c#

    If CreateFile fails then you have to call GetLastError to obtain the extended error information!
    Victor Nijegorodov

  3. #3
    Join Date
    Mar 2009
    Posts
    27

    Re: IPC from c++ to c#

    Quote Originally Posted by VictorN View Post
    If CreateFile fails then you have to call GetLastError to obtain the extended error information!
    Thanks for your answer.

    As result i get "1" ..
    Code:
    DWORD dw = GetLastError(); 
            MessageBox(NULL, (LPCSTR)dw  , "ERROR!", MB_OK);

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: IPC from c++ to c#

    Quote Originally Posted by boever View Post
    Code:
    ...
                          
        if ( !(pipeHandle != INVALID_HANDLE_VALUE ))
        {
     ....
    }
    Why is it so complicated? Why not just write:
    Code:
        if ( pipeHandle == INVALID_HANDLE_VALUE )
        {

    Quote Originally Posted by boever View Post
    Thanks for your answer.

    As result i get "1" ..
    Code:
    DWORD dw = GetLastError(); 
            MessageBox(NULL, (LPCSTR)dw  , "ERROR!", MB_OK);
    What does this strange casting ((LPCSTR)dw ) mean?
    You should write it in correct way as:
    Code:
    WORD dw = GetLastError(); 
    CString strMess;
    strMess.Format(_T("CreateFile failed with the code %d"), dw);
    AfxMessageBox(strMess);
    Victor Nijegorodov

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured