can i typecast like this?

Hi all,

i have pointer to an object (class A) in process A and i'm sending the content of this object to process B through some buffer (IPC). Now after receiving this data can i type cast the received content back to class A pointer and use it as class A object pointer. pseudo code is given below

class A{
int a;
}

In process A
A *Aobj = new A();
send((void *)Aobj,sizeof(class A))

In process B
void *buf;
allocate maximum size for this buf, which should be larger than receiving size
receive(buf,max_size);
(A *)buf ->a;

can i access a like this??

thanks in Advance.
You can do this with POD types if they don't contain any pointers (directly or indirectly).
A in your example is not a POD type, because it has a non-public member.
I'm pretty sure processes do not share memory space, so the answer would be "no" you can't do that.

In order to get memory shared by multiple processes you need to allocate it specially, often with OS specific functions. On Windows, iirc the function you want is GlobalAlloc.

Be very careful to clean up properly when you do this. IIRC, leaking with GlobalAlloc will cause a LEAK leak in that the memory won't be automatically freed when your program exits, and the only way to reclaim the memory would be to reboot.
Last edited on
^Why? I tried to test your claim with a RAM eater and expected a crash, but it only ate 2GB and stopped there. It also freed it all upon closing.

OS: Windows 7
I ran it in Visual Studio 2010, debug and release -- same result.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
	while(true)
	{
		GlobalAlloc(0, 1000); // Nom nom nom
	}
	system("pause"); //Perform great evil...
}
Last edited on
Perhaps I was mistaken! I remember reading something about that. Since globally allocated memory can be shared between processes, it is not owned by any one process, therefore the termination of the allocating process doesn't free the memory.

Although now that I look I can't find where I read that (this was a loooong time ago). And MSDN says nothing about it. And maybe I was remembering incorrectly.
Shared memory is done via memory-mapped files in Windows, GlobalAlloc just allocates memory on the heap.
But such leaks are indeed possible with POSIX shared memory objects.

Besides, transferring structures doesn't require any shared memory, unless the structures contain pointers and then you'd have to make sure the mapping starts at the same address in both processes.
Hi Athar,

why we need POD class here?

Actually this class is know by both process. so we have pointer to buffer which is content of that object of class A. what is the problem in accessing private member after type casting to class A.
its like copying the object itself right?

Topic archived. No new replies allowed.