当我在本地C代码中使用pin_ptr传递数组时,会出现访问冲突。 代码如下:
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有什么问题吗?