开发者

how to copy data? [closed]

开发者 https://www.devze.com 2023-01-06 01:08 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

I have a callback function which has the parameter const unsigned char *pData. everytime I hit the callback function I need to store the pData value into my local unsigned char* variable. Is there any function to copy the data?


Edit: Here is a code sample:

void Callbackfun(int x, const unsigned char* pData, const UINT cbData) {
    switch(x) {
 开发者_如何学运维   case 0:
        // ptr is a global variable of structure containg name and number
        ptr.name = (unsigned char*)pData;
        break;
    case 1:
        ptr.number = (unsigned char*)pData;
        break;
    }
}

now every time this function is called i want to store the pData values in my local structure (as shown by ptr.name).


In your callback function, you will have to allocate local memory for your "data". That way you can retain it when the calling function leaves scope. If you know the length of the data, and the length is consistent you have two options. Dynamic allocation, or allocate on the stack. Code example is untested.

Here's the dynamic allocation and copy.

 unsigned char* localData = new unsigned char[42];
 memcpy( localData, pData, 42 );

Here's the stack allocated version

 unsigned char localData[42];
 memcpy( &localData, pData, 42 );

I'm assuming you're not passing string data since you're using unsigned char. Since you're only dealing with a pointer you'll have to know the size of the buffer for either allocation.

If you do not have a constant data length, then you'll need to pass that as a second parameter to your callback function.


If you can alter the struct that ptr seems to be an instance of, I would suggest this:

#include <string>

struct ptr_type {
    std::string name;
    std::string number;
};

ptr_type ptr;

And for the callback, assuming cbData tells us the size of the buffer pointed to by pData:

void Callbackfun(int x, const unsigned char* pData, const UINT cbData) {

    // The following line will copy the buffer pointed to by
    // pData into an std::string object:
    std::string data(pData, cbData);

    switch(x) {
    case 0:
        // Simple assignment of std::string objects copies the
        // entire buffer:
        ptr.name = data;
        break;
    case 1:
        ptr.number = data;
        break;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消