RobVoisey
RobVoisey

Reputation: 1083

Problems with accessing Shared Memory using Large_Int

I am writing two applications, a producer and a consumer. My code is nearly identical to the MSDN example thus far :

http://msdn.microsoft.com/en-us/library/windows/desktop/aa366551%28v=vs.85%29.aspx

I have set up an event in the Producer which correctly triggers a response in the consumer. The producer creates a value in shared memory, and the consumer correctly responds, then opens the value and prints it via MessageBox.

However i am trying to get the producer to store a LARGE_INT rather than a tchar array. When i try to change CopyMemory to use a long instead, i get errors.

CopyMemory((PVOID)pBuf, timeStart, sizeof(long));

Any ideas on how i can modify it (again my code is near identical to the MSDN example) to store and retrieve a LARGE_INT?

Upvotes: 0

Views: 121

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490048

You're passing the value of timeStart, but you need to pass its address:

CopyMemory((PVOID)pBuf, (void *)&timeStart, sizeof(timeStart));

Edit: I should add, however, that I think this is generally the wrong way to go. With CopyMemory, you're basically turning everything into raw bits, which you then have to reconstitute into real data as it comes out the other end.

Instead of that, I'd generally prefer to do something like:

void *shared_base = whatever; // base address of shared memory segment

struct shared_data { 
    // The types of the data you actually need to share go here...
    LARGE_INTEGER x;
    int y;
    char z[512];
};

shared_data *data = (shared_data *)shared_base;

That much is basically the same on both sides. Then, on the producer side, you'd do something like:

data->x = my_large_integer;
SetEvent(data_ready);

...and on the consumer side, something like:

LARGE_INTEGER foo = data->x;
ResetEvent(data_ready);

This basically lets you do casting in one place, and then use the members of the structure directly, instead of having casts everywhere you need to access the shared data. Of course, you can get much more elaborate with it as well -- for example, if you want to be able to use (most of) the shared block for more than one purpose, you might use a union instead of a struct (or you might have a struct containing a union, etc., just like with any other code).

Upvotes: 1

Related Questions