在函数之间传递时指针未被更新

时间:2013-09-21 03:24:26

标签: c++ pointers dll

所以我的主要功能如下:

void main {
    uint32 errmsg;
    uint32 mydata;
    if (LOG) {
        std::ofstream file;
        file.open(fileName,ios_base::app);
        file << "!!!mydata: " << mydata << ",&mydata: " << &mydata << endl;
        file.close();
    }
    errmsg = ReadReg32(0, 0, &mydata);
    if (LOG) {
        std::ofstream file;
        file.open(fileName,ios_base::app);
        file << "!!! returned mydata: " << mydata << ",&mydata: " << &mydata << endl;
        file.close();
    }
}

并调用下面的ReadReg32:

static uint32 ReadReg32(uint32 brdNum, uint32 address, uint32 *data)
{
    std::ofstream file;
    if (LOG) {
        file.open(fileName,ios_base::app);
        file << "   ReadReg32: brdNum =" << brdNum << ", address =" << address << endl;
        file << "   ReadReg32 ... Data WAS:  " << *data << endl;
        file.close();
    }

    /* AD:TW Check if we need to do init */
    bool initstatus = checkDeferredInit();

    ADMXRC3_HANDLE phCard;
    ADMXRC3_STATUS status;

    //open card
    if((status = ADMXRC3_Open(brdNum, &phCard)) != ADMXRC3_SUCCESS)
        return status;

    //read data
    if((status = ADMXRC3_Read(phCard, NON_PREFETCHABLE_SPACE, 0, address, 4, &data)) != ADMXRC3_SUCCESS){
        ADMXRC3_Close(phCard);
        return status;
    }

    if (LOG) {
        file.open(fileName,ios_base::app);
        file << "   ReadReg32 ... Data IS:  " << data << ", &data: " << &data << ", Read status =" << status << endl;
        file.close();
    }

    //close card
    status = ADMXRC3_Close(phCard);

    if (LOG) {
        file.open(fileName,ios_base::app);
        file << "   ReadReg32 ... Close card status =" << status << ", Returning ..." << endl;
        file.close();
    }
    return status;
}

相关输出是:

!!!mydata: 348,&mydata: 000000000012F050
   ReadReg32: brdNum =0, address =0
   ReadReg32 ... Data WAS:  348
checkDeferredInit
   ReadReg32 ... Data IS:  0000000081040102, &data: 000000000012EF30, Read status =0
   ReadReg32 ... Close card status =0, Returning ...
!!! returned mydata: 348,&mydata: 000000000012F050

其中0000000081040102是我期望看到的正确数字,但它永远不会将其返回给调用函数,即mydata永远不会更新。

有趣的笔记:

  1. 在ADMXRC3_Read中,如果我不使用&amp;数据,我会得到“不正确的”数据值
  2. 在ADMXRC3_Read中,我坚持使用&amp;数据的类型是 应该是无效的* pbuffer?
  3. 任何想法都值得一提,如啤酒或中等优质的盒装葡萄酒。 ;)

    我很感激你的任何想法,这让我很难过......

1 个答案:

答案 0 :(得分:2)

乍一看,您似乎过多地使用&

static uint32 ReadReg32(uint32 brdNum, uint32 address, uint32 *data)
{
 ....
//read data
    if((status = ADMXRC3_Read(phCard, NON_PREFETCHABLE_SPACE, 0, address, 4, &data)) != ADMXRC3_SUCCESS){
        ADMXRC3_Close(phCard);
        return status;
    }

read data部分中,您使用ADMXRC3_Read参数调用&data。但是data已经是指针!所以你实际上传递了函数本地变量的地址。

要解决此问题,请仅使用ADMXRC3_Read致电data

重要事项:在C和C ++中,所有内容都按值传递!因此data只是一个包含32位数字的变量(如果你有32位地址),仅此而已。< / p> 编辑:在我的笔记中,我指的是这个常见问题解答:http://c-faq.com/ptrs/passbyref.html我写错了。有关详细信息,请参阅常见问题解答。