Help constructing `PackedByteArray` from native C types GDExtension

Godot Version

4.4

Question

Hello!

I’m using Godot 4’s GDExtension system to try to build bindings to a C++ library, and I’ve found a spot where I can’t seem to find a streamlined solution.

I’m trying to pack an array uint8_t* into a PackedByteArray so that I can return it back to Godot.

Specifically, I want to use that PackedByteArray in the constructor for Image, since that’s what the data represents.

None of the constructors for PackedByteArray takes uint8_t*, nor anything that sticks out to me as an intermediary format.

If there isn’t a proper solution, I could copy each byte’s data individually, but that would be really slow..

For context, I’m trying to write a binding from Stable Diffusion.cpp to Godot. I need to be able to cast between sd_image_t and godot::Image.

typedef struct {
    uint32_t width;
    uint32_t height;
    uint32_t channel;
    uint8_t* data;
} sd_image_t;

Is this reasonably possible?

Thanks in advance for the help!

Sadly I do not believe they have a moving/taking ownership constructor for the packed array. Godot like it’s allocator more than yours.

You could copy pretty fast by making a new packed array, resize it, then get a writable pointer

PackedByteArray output;
output.resize(image_total_size);
uint8_t *write = output.ptrw();
for (size_t i = 0; i < image_total_size; i++) {
    *write = *image.data;
}
// or!
std::memcpy(write, image.data, image_total_size)

It certainly won’t be the slowest part of stable diffusion image generation haha

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.