本文介绍了使用 pin_ptr 时访问冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用 pin_ptr 在本机 c 代码中传递数组时,出现访问冲突.代码如下:
When I use pin_ptr to pass an array in native c code, I get access violation. The code is as bellow:
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;
}
当我更改此代码以分配新空间并将原始数组复制到该代码时,我没有遇到访问冲突.新代码:
When I changed this code such that allocate new spaces and copy original array to that, I didn't get access violation.New code:
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 时有什么问题吗?
Question: Are there any problem in my using from pin_ptr?
推荐答案
正如文档所说,pin_ptr
只在目标范围内固定目标.这意味着在以下循环的每次迭代之后,对象将被取消固定,从而使存储的指针变得无用.
As the docs say, pin_ptr
only pins the target while it is in scope. This means that after each iteration of the following loop, the object is unpinned, rendering the pointers that were stored useless.
for(i = 0; i < modelsNum; i++)
{
pin_ptr<unsigned char> ptr = &modelsBuffer[i][0];
models[i] = (float*) ptr;
}
这篇关于使用 pin_ptr 时访问冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!