我正在尝试通过 shared_ptr 访问我之前使用 calloc
方法分配的数据。出于某种原因,我无法在 glTexImage2D
(我的代码片段的最后一行)上访问它(继续使用 EXC_BAD_ACCESS
崩溃)。
我加载数据的util方法:
shared_ptr<ImageData> IOSFileSystem::loadImageFile(string path) const
{
// Result
shared_ptr<ImageData> result = shared_ptr<ImageData>();
...
// Check if file exists
if([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:NO])
{
...
GLubyte *spriteData = (GLubyte*) calloc(width * height * 4, sizeof(GLubyte));
...
// Put result in shared ptr
shared_ptr<GLubyte> spriteDataPtr = shared_ptr<GLubyte>(spriteData);
result = shared_ptr<ImageData>(new ImageData(path, width, height, spriteDataPtr));
}
else
{
cout << "IOSFileSystem::loadImageFile -> File does not exist at path.\nPath: " + path;
exit(1);
}
return result;
}
ImageData
的 header :
class ImageData
{
public:
ImageData(string path, int width, int height, shared_ptr<GLubyte> data);
~ImageData();
string getPath() const;
int getWidth() const;
int getHeight() const;
shared_ptr<GLubyte> getData() const;
private:
string path;
int width;
int height;
shared_ptr<GLubyte> data;
};
调用util类的文件:
void TextureMaterial::load()
{
shared_ptr<IFileSystem> fileSystem = ServiceLocator::getFileSystem();
shared_ptr<ImageData> imageData = fileSystem->loadImageFile(path);
this->bind(imageData);
}
void TextureMaterial::bind(shared_ptr<ImageData> data)
{
// Pointer to pixel data
shared_ptr<GLubyte> pixelData = data->getData();
...
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, data->getWidth(), data->getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixelData);
}
仅作记录:如果我丢弃所有 shared_ptr,我就可以访问数据。 glTexImage2D
的签名:
void glTexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data);
附加问题:通常你必须释放(spriteData)但是因为我把数据给了一个 shared_ptr,当 shared_ptr 被移除时数据会被释放吗?
最佳答案
shared_ptr
无法神奇地猜测如何释放内存。默认情况下,它会尝试删除
它,并且由于您没有使用new
,所以最终会导致灾难。
你需要告诉它怎么做:
shared_ptr<GLubyte>(spriteData, &std::free);
关于c++ - 通过 shared_ptr 访问 calloc 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11777119/