Function to create sdl2 Texture


#1

I have much to learn with Rust still, I’m experimenting with the sdl2 rust crate. I’d like to write a function that returns a newly created Texture. These are bound to the lifetime of the Canvas they are created for, so I figured a function that took a canvas reference as an argument and returned a new Surface sharing its lifetime?

I cannot determine the function signature that will compile. This is likely tricky due to the generic types and lifetime references I’ll need to make. The primary sdl2 classes are the Canvas and Texture.

I believe the signature should look like: (the compiler disagrees)

fn loadtex<'r, T: Window>(canvas: & Canvas<T>) -> &Texture

One of my problems is that Canvas requires an additional trait for the create_texture function I’m wanting, so I need to specify something, but can only find a struct that implements the function I want. Window, I am told, is not a trait.


#2

I think you want Canvas<Window> - that’s a concrete Canvas type. Or are you dealing with an arbitrary RenderTarget?

Textures are created by TextureCreator. You need to get a creator via Canvas::texture_creator(&self). Note that textures created by TextureCreator have a lifetime associated with the creator it came from, not the Canvas. As such, you’ll need to keep the TextureCreator alive for as long as you have/need textures from it to be alive.


#3

Yes, these were the tips I needed. I didn’t realize the TextureCreator controlled the lifetime, but it’s right there in the documentation.

In the end I didn’t even need to specify the lifetimes. Magic Rust (nightly 1.24) figured it out:

fn loadtex<T>(creator: &TextureCreator<T>) -> Texture