Use DllImport attribute to invoke functions in a native DLL

I need to transfer information through shared memory between 2 exe files. I've found a C++ code that pretty much do exactly what I need to do, but I don't know how to do it in C#.

Is there a way to convert this code to C# or write something in C# and would be able to receieve information for the C++ code

Sample C++ Code:

#include <windows.h>
#include <stdio.h>
#include <conio.h>

#define BUF_SIZE 256
TCHAR szName[]=TEXT("MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process");

void main()
{
  HANDLE hMapFile;
  LPCTSTR pBuf;

  hMapFile = CreateFileMapping(
         INVALID_HANDLE_VALUE,  // use paging file
         NULL,          // default security 
         PAGE_READWRITE,     // read/write access
         0,            // max. object size 
         BUF_SIZE,        // buffer size 
         szName);         // name of mapping object
 
  if (hMapFile == NULL || hMapFile == INVALID_HANDLE_VALUE) 
  { 
   printf("Could not create file mapping object (%d).\n", 
       GetLastError());
   return 1;
  }
  pBuf = (LPTSTR) MapViewOfFile(hMapFile,  // handle to map object
            FILE_MAP_ALL_ACCESS, // read/write permission
            0,          
            0,          
            BUF_SIZE);      
 
  if (pBuf == NULL) 
  { 
   printf("Could not map view of file (%d).\n", 
       GetLastError()); 
   return 2;
  }

  
  CopyMemory((PVOID)pBuf, szMsg, strlen(szMsg));
  getch();

  UnmapViewOfFile(pBuf);

  CloseHandle(hMapFile);

  return 0;
}
 


Answer this question

Use DllImport attribute to invoke functions in a native DLL

  • Alexander R.

    It works.

    Thanks.


  • javierprior1

    I am trying this code out and will let you know if it works soon.

    I have one more question. I am doing some reading on serialization. I am just wondering if I would be able to transfer information back and forth from the memory that way too

    Also, the code that sends in the binary would be written in C and the receiving code would be in C#. Would it be possible to send in the info using memory-mapped and receieve it using serliaization (I am still trying to understand how serliaization differnt from a regular shared memory)

    Thanks for the help. I really appreciate it.


  • Steve Murrell

    You may use DllImport to do this.

    Declare all function you needed like this:

    class SharedMemoryAPIs

    {

    [DllImport("user32.dll")] //use this attribute to import an Windows API from an DLL 

    public static Handle CreateFileMapping( Handle fileHandle,Int32 securityDescription,Int32 access,Int32 bufferSize,String name );

    //Declare other APIs you needed here

    };

    And then you can use these APIs just like a normal C# static method.



  • Use DllImport attribute to invoke functions in a native DLL