调用包含free()方法的本机dll的方法时出现'System.AccessViolationException'

时间:2016-08-25 12:52:54

标签: c# exception malloc native free

我使用本机C ++代码返回指向使用CUDA分配的图形卡上的某些内存的指针,以便稍后调用CUDA方法来处理此数据。这工作正常,但我存储在图形卡上的数据从文件读取到char数组,然后将这些数据复制到图形卡。由于char数组是使用malloc()创建的,因此当数据被复制到图形卡后,该方法当然会自由调用。由于数据相当大,我真的要清理数组。但是只要该方法包含free(pcDataFromDisk);调用C#代码的方法时出现'System.AccessViolationException'。 本机方法如下所示:

extern "C" DLLEXTERN char* getDeviceCharPointerToPrerasteredImageDataWithSize(char* a_filename, int &a_iSizeByte, bool a_bImediateFree) {
char* ptrReturn = NULL;
char* ptr_host = ReadPrerasteredImageFileIntoDeviceMemoryAsChar(a_filename);
//copy char-array to graphic card memory:
cudasafe(cudaMalloc((void **)&ptrReturn, a_iSizeByte), "Original image allocation ", __FILE__, __LINE__);
(cudaMemcpy(ptrReturn, ptr_host, a_iSizeByte, cudaMemcpyHostToDevice);
free(ptr_host); //This line causes the 'System.AccessViolationException' when the method is called from C#.
return  ptrReturn;}

将文件读取到缓冲区的方法类似于

ReadPrerasteredImageFileIntoDeviceMemoryAsChar(){
…
buffer = (char *)malloc((filelen);
fread(buffer, filelen, 1, fileptr); // Read in the entire file
fclose(fileptr); // Close the file
return buffer;}

我还尝试使用指向char-array的静态指针将'free()'放入一个单独的方法中,但是调用FreeData(){free(_pcDiskData);}相同的'System.AccessViolationException'就是结果。当C#打算调用本机方法时,如何将数据读入本机代码中的char数组并在之后释放它?感谢您的帮助,Jürgen

0 个答案:

没有答案