Hi,
In my never ending quest to improve my C++, I'm trying to write a class that sets and reads shared memory. For the time being I am avoiding dealing with issues of concurrency/locking, etc. and starting small. I was successfully able to put into shared memory things like integers, char *, and even my own custom classes. (By making it a templated class).
However, I seem to be running into a problem if I attempt to use either a datatype or a class that contains a member that is of a datatype 'non native', ie like a 'string', or 'vector', I either crash or get garbage. I'm coming to the conclusion that I simply can't store these datatypes, given that the shared memory is 'C' code rather than C++. Could you confirm my assumption that it basically can't handle C++ types, or is it something in my code that would cause this problem?
Below is my SharedMemory class. (Note that all code is in the .h file right now - I'll separate it out when I use it more officially).
extern "C"
{
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
}
template <class InputClass>
class SharedMemory
{
private:
key_t key;
int shmid;
InputClass *data;
int SHM_SIZE;
string fileName;
void initialize()
{
if ((key = ftok(fileName.c_str(), 'R')) == -1)
{
throw DHException( "*** Could not connect to shared memory file [" + fileName + "] Check that the file exists...***" );
}
/* connect to (and possibly create) the segment: */
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1)
{
throw DHException( "*** Could not use shared memory file: [" + fileName + "] Check that the allocated size is OK..***");
}
data = (InputClass *) shmat(shmid, 0, 0);
if (data == (InputClass *)(-1))
{
throw DHException ( "*** Could not connect to shared memory file:(error 3):" + fileName);
}
}
public:
SharedMemory( string file )
{
SHM_SIZE=sizeof(InputClass);
fileName = file;
initialize();
}
SharedMemory( int size, string file )
{
SHM_SIZE=size;
fileName = file;
initialize();
}
void writeToSharedMemory( InputClass ic )
{
*data = ic;
}
InputClass getFromSharedMemory( )
{
return *data;
}
~SharedMemory()
{
if (shmdt((char *)data) == -1)
{
throw DHException ( "Could not disconnect from shared memory file:" + fileName );
}
}
int getMemorySize() { return SHM_SIZE; }
An example of usage would be (where Date is a custom class of mine that only contains native types like int's, time_t, etc.):
SharedMemory<Date> shm(1000, "DANTEST" );
while ( true )
{
Date a;
shm.writeToSharedMemory(a);
screenLog<<"Just Placed:"<<a<<endl;
sleep( 1 );
}