Home > front end >  shared memory c cross platform
shared memory c cross platform

Time:05-09

I'm coding in c a program that works as a socket between other programs in different languages (C#, python till now). This socket reads data from the USB-port, do some stofe and stream it to the other programs.

My Idea: each program asks over a port-massage to be part of the stream. As response this program gets a pointer to a shared memory. Is this possible? shared memory over different programing-languages? and can I just passe the pointer to the shared memory to the other program? and is there a way to do it cross-platform ? (UNIX and WINDOWS)

best wishes Knut

CodePudding user response:

Is this possible? shared memory over different programing-languages?

Yes. Memory is memory, so a shared-memory region created by language A can be accessed by a program written in language B.

and can I just passe the pointer to the shared memory to the other program?

It's not quite that simple; the other program won't be able to access the shared-memory region until it has mapped that same region into its own virtual-address space, using shmat() or MapViewOfFile() or similar.

Note that the shared-memory region will likely be mapped to a different range of addresses in each process that is attached to it, so don't rely on the pointer to a piece of shared data in process A being the same as a pointer to that same data in process B.

and is there a way to do it cross-platform ?

It looks like boost has an API for shared memory, if you want to go that route. Alternatively, you could write your own shared-memory API, with different code inside the .cpp file for Windows and POSIX OS's, with appropriate #ifdefs. That's how I did it in my library, and it works okay.

CodePudding user response:

As an alternaive to using shared memory, you can consider named pipes.
Some general information: Named pipe - Wikipedia.

Named pipes API is more high-level than shared memory.
Instead of having a raw block of memory you need to manage yourself (including using some kind of interporocess locking mechanism like named mutex to access shared data), you get a transport layer for messages.

Performance-wise they are quite efficient. But of course you will have to profile it for your specific case.

The API is available for all languages that you mentioned (and many more):
For C# (on Windows): How to: Use Named Pipes for Network Interprocess Communication.
For C : on Windows: Named Pipes - Win32, and Linux: Named pipes - Linux.
For Python: Python named pipes.

  •  Tags:  
  • c
  • Related