473,748 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Shared Memory Example (Python, ctypes, VC++)

Hello,
Here are code snippets to create and access shared memory in Python
with and without ctypes module.

With regards,
Srijit

Filename : SharedMemCreate .py

import msvcrt, mmap
from ctypes import *

FILE_MAP_ALL_AC CESS = 0xF001F
INVALID_HANDLE_ VALUE = 0xFFFFFFFF
SHMEMSIZE = 256
PAGE_READWRITE = 0x04
szName = c_char_p("MyFil eMappingObject_ ctypes")
szMsg = "Message from Python(ctypes) process"

hMapObject = windll.kernel32 .CreateFileMapp ingA(INVALID_HA NDLE_VALUE,
None, PAGE_READWRITE, 0, SHMEMSIZE, szName)
if (hMapObject == 0):
print "Could not open file mapping object"
raise WinError()

pBuf = windll.kernel32 .MapViewOfFile( hMapObject, FILE_MAP_ALL_AC CESS,
0, 0, SHMEMSIZE)
if (pBuf == 0):
print "Could not map view of file"
raise WinError()
else:
memcpy = cdll.msvcrt.mem cpy
memcpy(pBuf, szMsg, len(szMsg))

shmem = mmap.mmap(0, 256, "MyFileMappingO bject", mmap.ACCESS_WRI TE)
shmem.write("Me ssage from Python process")

msvcrt.getch()

windll.kernel32 .UnmapViewOfFil e(pBuf)
windll.kernel32 .CloseHandle(hM apObject)
shmem.close()

Filename : SharedMemAccess .py

from ctypes import *
import mmap

FILE_MAP_ALL_AC CESS = 0xF001F
INVALID_HANDLE_ VALUE = 0xFFFFFFFF
FALSE = 0
TRUE = 1
SHMEMSIZE = 256
szName = c_char_p("MyFil eMappingObject" )

hMapObject = windll.kernel32 .OpenFileMappin gA(FILE_MAP_ALL _ACCESS,
FALSE, szName)
if (hMapObject == 0):
print "Could not open file mapping object"
raise WinError()

pBuf = windll.kernel32 .MapViewOfFile( hMapObject, FILE_MAP_ALL_AC CESS,
0, 0, 0)

if (pBuf == 0):
print "Could not map view of file"
raise WinError()
else:
pBuf_str = cast(pBuf, c_char_p)
print pBuf_str.value

windll.kernel32 .UnmapViewOfFil e(pBuf)
windll.kernel32 .CloseHandle(hM apObject)

shmem = mmap.mmap(0, 256, "MyFileMappingO bject_ctypes",
mmap.ACCESS_REA D)
print shmem.read(64)
shmem.close()
Source code to access shared memory, created in Python, from VC++
program

// Cplusplus_Share dMemoryAccess.c pp : Defines the entry point for the
console application.
//

#include "stdafx.h"
using namespace std;

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

#define SHMEMSIZE 256

HANDLE hMapObject = NULL; // handle to file mapping
LPCTSTR pBuf;
TCHAR szName[]= TEXT("MyFileMap pingObject");

int _tmain(int argc, _TCHAR* argv[])
{
hMapObject = OpenFileMapping (
FILE_MAP_ALL_AC CESS, // read/write access
FALSE, // do not inherit the name
szName // name of mapping object
);

if (hMapObject == NULL || hMapObject == INVALID_HANDLE_ VALUE) {
cout << "Could not open file mapping object " << GetLastError()
<< endl;
return 0;
}
pBuf = (LPTSTR) MapViewOfFile(h MapObject, // handle to mapping
object
FILE_MAP_ALL_AC CESS, // read/write
permission
0,
0,
SHMEMSIZE
);

if (pBuf == NULL)
{
cout << "Could not map view of file " << GetLastError() << endl;

return 0;
}

cout << "pBuf = " << pBuf << endl;
MessageBox(NULL , pBuf, TEXT("Process2" ), MB_OK);

UnmapViewOfFile (pBuf);
CloseHandle(hMa pObject);

return 0;
}

Jul 18 '05 #1
1 7664
Thanks.


Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
4408
by: Srijit Kumar Bhadra | last post by:
Hello, Here is some sample code with pywin32 build 203 and ctypes 0.9.6. Best regards, /Srijit File: SharedMemCreate_Mutex_win32all.py # This application should be used with SharedMemAccess_Mutex_ctypes.py or SharedMemAccess_Mutex_win32all.py
5
4437
by: Claudio Grondi | last post by:
Background information: --------------------------------- in order to monitor mainboard sensory data as fan speeds, temperatures, applications like SpeedFan http://www.almico.com/speedfan.php or MBM http://mbm.livewiredev.com/ can be used. Both of the mentioned apps expose data got from the hardware in a shared memory area.
3
2144
by: alanrn | last post by:
I would like to start a dialog on how to implement the equivalent functionality of UNIX shared memory in .NET. I work with a factory automation system. The bulk of the system is written in C/C++. It was ported from UNIX to run under Windows using .NET. If for no other reason than as an educational exercise, I have been wondering what it would take to rewrite the system under C#. The system currently has about a 100K “shared...
1
1921
by: Gerald Klix | last post by:
I read the whol email thread carefully and could not find any sentence by Guido, which states that he does not accept ctypes for the standard library. He just declined to rewrite winreg. Did I miss something? Cya, Gerald -----Ursprüngliche Nachricht----- Von: python-list-bounces+gerald.klix=klix.ch@python.org Im Auftrag von
2
1630
by: Sebastjan Trepca | last post by:
Hey! Are there any "live" modules for working with shared memory in Python? I found some but they are all dead(posh,shm)... Thanks, Sebastjan
0
2276
by: follower | last post by:
This post is mostly Google-bait for anyone else that might want to compile SpiderMonkey ( libjs / libjs.so / libjs.dylib ) for OS X (10.4.5 in my case) and then use it with Python's ctypes. I can't say this will work for anyone else, but it worked for me... Using: http://ftp.mozilla.org/pub/mozilla.org/js/js-1.5.tar.gz First up:
0
1031
by: Nikita the Spider | last post by:
Hi all, In the late 90s Vladimir Marangozov wrote a module that provided an interface to System V shared memory on *nix platforms. I found a copy on the Net, dusted it off, compiled it, plugged a couple of memory leaks, intergrated others' changes, etc. Vlad hasn't posted on Usenet since the summer of 2000 and I can't find a working email address for him, so I assume this module is orphaned; this is a last-ditch effort to track him down...
5
5277
by: Tim | last post by:
Hello Everyone, I am getting shared memory in python using the following. szName = c_char_p(name) hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE, None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName) if (hMapObject == 0): print "OpenKey: Could not open name file mapping object" raise WinError()
2
1677
by: gaurav kashyap | last post by:
Dear all, I have a server program that listens to a particular port and a number of client programs that connect to the server. Now i want to put some data in form of python list in main memory on server.Hence whenver a client program is run it connects to the server and access the data in main memory.Here the server calls a module that processes the data as per the client request and the returns some information to the client.
0
8818
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9355
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9307
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9225
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8234
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4589
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4860
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3296
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.