I have a problem setting an array equel to an array that I retrieve from memory (using boost library). First I could imagine that the array that I get from the memory wasn't valid. But a couple of test later I ruled that out. My code:
sending code:
1 2 3 4 5 6 7 8 9 10 11 12 13
usingnamespace boost::interprocess;
shared_memory_object::remove("MySharedMemory");
managed_shared_memory segment(create_only, "MySharedMemory", 955360);
unsignedchar data[] = {100, 100, 100, 100, 100, 100, 100, 100, 100};
unsignedchar *array_it = segment.construct_it<unsignedchar>
("MyType array from it") //name of the object
[9]] //number of elements
( &data[0] ); //Iterator for the 1st ctor argument
receiving code:
1 2 3 4 5 6 7 8 9 10 11
unsignedchar *receivedData = newunsignedchar[9];
usingnamespace boost::interprocess;
std::pair<unsignedchar*, std::size_t> res;
managed_shared_memory segment(open_only ,"MySharedMemory");
//Find the array constructed from iterators
res = segment.find<unsignedchar> ("MyType array from it");
receivedData = res.first;
This doesn't work. But when I use the following code:
1 2 3 4
for (int k = 0; k < 9; k++)
{
receivedData[k] = res.first[k];
}
the array is correctly filled. But the array can be a lot bigger as the array used in this example, so a for loop isn't usable because of performance issues.
Is there a way to set the array equal to the incoming array?
What am I doing wrong?
Any suggestions or tips are highly appreciated!
-Ray
if the arrays continually differ in size you can use the strlen command in a loop to set the number of iterations in respect to the size of the string ie;
for (i = 0; i <=strlen(k)-1; i++) recieved Data[i] = res.first[i];
for (int k = 0; k < 9; k++)
[edit]: you subtract 1 often from the strlen command because arrays start at the k[0] position
BettyBoopTS,
Thank you so much for that fast response!
The length of the array doesn't vary in size.
The problem I'm having is that for loops take up to much processing power on the arrays I'm using.
If I initialize an array of the same length and type as the array that's coming in, why can't I set those two alike, or copy the contents of array1 in 2 without looping trough all the values individually?
I actually was running out the door right after the last post I just got back. There is the strcpy function which will copy the contents of 1 string to another. A call to strcpy takes this general form:
strcpy(to, from); so if you wanted to copy a character array , just remember the array that it copies it into be initialized to be large enough to hold the string that is sending it.
1 2 3 4
s1 would recieve the entire contents of s2
strcpy (s1,s2);
Or you can use strcpy_s(), which checks that the 'to' c-string can fit all of the 'from' string. Otherwise, it fits in as much as possible (including a '\0' at the end). Sure, you'll still not have what you want, but at least you won't have a buffer overflow.