使用pin_ptr时访问冲突?

时间:2012-12-21 12:31:48

标签: c++-cli access-violation pin-ptr

当我使用pin_ptr在本机c代码中传递数组时,我会遇到访问冲突。代码如下:

array<float>^ LogLikelihoodScore(array<array<unsigned char>^>^ modelsBuffer , array<float>^ featuresArray, int numberOfFrames)
{
    int i, j, modelsNum = modelsBuffer->Length, len;
    float **models = (float**) malloc(modelsNum * sizeof(void*));
    for(i = 0; i < modelsNum; i++)
    {
        pin_ptr<unsigned char> ptr = &modelsBuffer[i][0];
        models[i] = (float*) ptr;
    }
    array<float>^ scores = gcnew array<float>(modelsNum);
    pin_ptr<float> scoresPtr = &scores[0];
    pin_ptr<float> featuresPtr = &featuresArray[0];
    char* message = CalculateLikelihoodUsingBufferedModels(models, modelsNum, featuresPtr, numberOfFrames, scoresPtr);
    return scores;
}

当我更改此代码以便分配新空格并将原始数组复制到该代码时,我没有获得访问冲突。 新代码:

array<float>^ LogLikelihoodScore(array<array<unsigned char>^>^ modelsBuffer , array<float>^ featuresArray, int numberOfFrames)
{
    int i, j, modelsNum = modelsBuffer->Length, len;
    float **models = (float**) malloc(modelsNum * sizeof(void*));
    for(i = 0; i < modelsNum; i++)
    {
        len = modelsBuffer[i]->Length;
        char* ptr = (char*) malloc(len);
        pin_ptr<unsigned char> ptr2 = &modelsBuffer[i][0];
        memcpy(ptr, ptr2, len);
        models[i] = (float*) ptr;
    }
    array<float>^ scores = gcnew array<float>(modelsNum);
    pin_ptr<float> scoresPtr = &scores[0];
    pin_ptr<float> featuresPtr = &featuresArray[0];
    char* message = CalculateLikelihoodUsingBufferedModels(models, modelsNum, featuresPtr, numberOfFrames, scoresPtr);
    return scores;
}

问题:我在使用pin_ptr时遇到任何问题吗?

1 个答案:

答案 0 :(得分:3)

  

当钉扎指针超出范围时,该对象不再被视为固定,除非有其他钉扎指针指向或进入对象。您不必明确取消指针。

正如the docs所述,pin_ptr仅在目标处于范围时将其定位。这意味着在下一个循环的每次迭代之后,取消固定对象,使得存储的指针无用。

for(i = 0; i < modelsNum; i++)
{
    pin_ptr<unsigned char> ptr = &modelsBuffer[i][0];
    models[i] = (float*) ptr;
}