内存模型
CUdeviceptr:cuda中的指针,用于指向一为显存。注意为Drive接口指针。
CUarray:用来标出cuda中的二维显存。
具体使用方式如下。
/**
*@brief 展示显存使用的代码,使用的编译工具是visual studio 2013。
*/
#include <fstream>
#include <string>
#include <iostream>
#include <cstdint>
using namespace std;
#include <cuda.h>
#include <cuda_runtime_api.h>
/**
*@brief 二进制文件的读写操作。
*/
int32_t main()
{
try {
string inFileName = "F:\\Middleware\\In.bgra";
string outFileName = "F:\\Middleware\\Out.bgra";
int32_t width = 1920;
int32_t height = 1080;
ifstream inFile;
ofstream outFile;
uint8_t *RGBA = new uint8_t[width * height * 4];
uint8_t *outRGBA = new uint8_t[width * height * 4];
inFile.open(inFileName.c_str(), ios::binary);
if (!inFile.is_open())
throw inFileName;
outFile.open(outFileName.c_str(), ios::binary);
if (!outFile.is_open())
throw outFileName;
//为cudaArray分配内存。4个分量,每个分量为8bit无符号的整数。
cudaArray *cuInputArray;
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc(8, 8, 8, 8, cudaChannelFormatKindUnsigned);
cudaMallocArray(&cuInputArray, &channelDesc, width, height, cudaArrayDefault);
//为CUdeviceptr分配内存。注意CUdeviceptr是Drive内存,不是Runtime内存,但
CUdeviceptr outCuMemory;
void *cudaOutMemory = nullptr;
cudaMalloc(&cudaOutMemory, width * height * 4);
outCuMemory = (CUdeviceptr)cudaOutMemory;
int32_t i = 0;
for (i = 0; i < 20; i++) {
inFile.read((char *)RGBA, width * height * 4);
//cudaMemcpy2DToArray()经测试,所有的宽度、高度、pitch的单位都是字节,而不是像素。
//拷贝数据,从主机内存到显卡内存Array。
cudaMemcpy2DToArray(cuInputArray, 0, 0, RGBA, width * 4, width * 4, height, cudaMemcpyHostToDevice);
//图像处理部分
//拷贝数据,从显卡内存Array到显卡线性内存。
cudaMemcpy2DFromArray(cudaOutMemory, width * 4, cuInputArray, 0, 0, width * 4, height, cudaMemcpyDeviceToDevice);
//拷贝数据,从显卡线性内存到主机内存。
cudaMemcpy(outRGBA, cudaOutMemory, width * height * 4, cudaMemcpyDeviceToHost);
outFile.write((char *)outRGBA, width * height * 4);
}
cudaFreeArray(cuInputArray);
cuMemFree(outCuMemory);
cudaFree(cudaOutMemory);
if (RGBA != nullptr)
{
delete[] RGBA;
RGBA = nullptr;
}
if (outRGBA != nullptr)
{
delete[] outRGBA;
outRGBA = nullptr;
}
if (inFile.is_open()) {
inFile.clear();
inFile.close();
}
if (outFile.is_open()) {
outFile.clear();
outFile.close();
}
return 0;
}
catch (const bad_alloc &e) {//内存分配异常
cerr << __FILE__ << "(" << __LINE__ << "):Unable to allocate memory!" << endl;
cerr << e.what() << endl;
return -1;
}
catch (string s) {//文件打开异常
cerr << __FILE__ << "(" << __LINE__ << ")" << s.c_str() << endl;
return -1;
}
catch (...) {//其他异常
cerr << "发生了没有定义的异常" << endl;
return -1;
}
}