我正在寫freeimage的一個小包裝器,用於圖像加載和像素抓取等等。我有一個PImage
類,它負責處理所有的加載和顯示,並且裏面有一個PixelColorBuffer
類。我使用PixelColorBuffer
來方便地從texturebuffer
中抓取unsigned char
,並將它們轉換成另一個叫做color
的類(因爲它工作正常,我排除了它)。我也希望能夠使用這個PixelColorBuffer
類來設置像素,這就是爲什麼它具有colortobuffer
和buffertocolor
。我使用指向unsigned char array
的指針實例化PixelColorBuffer
(注意:它包含圖片的rgba值)。然而,這似乎工作,但是當我打電話get(10, 10)
被裝載在圖像上,並顯示我得到以下幾點:Segfault指向數組訪問的指針
(GNU Debugger)
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7bc66d9 in cprocessing::PixelColorBuffer::buffertocolor (this=<optimized out>, n=<error reading variable: Unhandled dwarf expression opcode 0x0>) at pixelcolorbuffer.cpp:17
17 c.rgba[0]=(*b)[(n*4)+0];
的PImage
和PixelColorBuffer
類被編譯成.so
和鏈接正確。我假設我在設置指針時做了一些錯誤,這是我第一次處理指向指針的指針......但我不能爲我的生活弄清楚我做錯了什麼。這裏是所有相關的代碼。
///MAIN_PROGRAM.CPP
PImage t;
t.loadImage("image.png"); //loads image (works)
image(t, mouseX, mouseY); //draws image (works)
color c = t.get(10, 10); //SEGFAULT
///PIMAGE.HPP
class PImage {
public:
GLubyte * texturebuffer; //holds rgba bytes here
PixelColorBuffer * pixels;
PImage();
color get(int x, int y);
};
///PIMAGE.CPP
PImage::PImage() {
this->pixels = new PixelColorBuffer((unsigned char *) texturebuffer);
}
void PImage::loadImage(const char * src) {
//...snip...freeimage loading/opengl code ...
char * tempbuffer = (char*)FreeImage_GetBits(imagen);
texturebuffer = new GLubyte[4*w*h];
//FreeImage loads in BGR format, so we swap some bytes
for(int j= 0; j<w*h; j++){
texturebuffer[j*4+0]= tempbuffer[j*4+2];
texturebuffer[j*4+1]= tempbuffer[j*4+1];
texturebuffer[j*4+2]= tempbuffer[j*4+0];
texturebuffer[j*4+3]= tempbuffer[j*4+3];
}
//...snip...freeimage loading/opengl code ...
}
color PImage::get(int x, int y) {
return pixels->buffertocolor((y*w)+x);
}
///PIXELCOLORBUFFER.HPP
class PixelColorBuffer {
public:
unsigned char ** b;
PixelColorBuffer(unsigned char * b);
/**Converts a pixel from the buffer into the color
* @param n pixel ((y*width)+x)
* @return color*/
color buffertocolor(int n);
/**Converts a pixel from the buffer into the color
* @param n pixel ((y*width)+x)
* @param c color to put into buffer*/
void colortobuffer(int n, const color& c);
};
///PIXELCOLORBUFFER.CPP
PixelColorBuffer::PixelColorBuffer(unsigned char * b) {
this->b = &b;
}
color PixelColorBuffer::buffertocolor(int n) {
color c(0, styles[styles.size()-1].maxA);
c.rgba[0]=(*b)[(n*4)+0];
c.rgba[1]=(*b)[(n*4)+1];
c.rgba[2]=(*b)[(n*4)+2];
c.rgba[3]=(*b)[(n*4)+3];
return c;
}
void PixelColorBuffer::colortobuffer(int n, const color& c) {
(*b)[(n*4)+0] = c.rgba[0];
(*b)[(n*4)+1] = c.rgba[1];
(*b)[(n*4)+2] = c.rgba[2];
(*b)[(n*4)+3] = c.rgba[3];
}
我猜首先我會問,你的圖像大於10乘10? – Xymostech
此代碼不完整也不正確,我敢打賭這不是最小的。 – Beta
是的。幾百到幾百。如果是這樣的話,那將很有趣。 – jett