Zebrafish
Zebrafish

Reputation: 13936

Is this void* hack bad?

In a header I defined a class function like this:

struct SDL_Window; // Forward declaration

struct SomeClass
{
     void createVulkanSurface(SDL_Window* SDL_window, VkInstance vkInstance, VkSurfaceKHR vkSurface);
};

So the compiler doesn't know what VkInstance and VkSurfaceKHR are. They are typedefs defined by a macro. They may be typed pointer, or a uint64_t, it's just a handle. I think the only safe thing (instead of forward declaring these and risking the types changing) is to include the vulkan.h header that defines these typedefs, but I don't want to do that because it's a big header and it'll also be included in anything I include my .h header in. I had the idea changing the function signature to:

void createVulkanSurface(SDL_Window* SDL_window, void* vkInstance, void* vkSurface);

And then in the .cpp where I define this function to cast back to VkInstance and VkSurface. I know this is safe as void* pointers can be converted to and from any pointer type. In the case the typedef is of a uint64_t then a cast to void* and back may narrow the value as a pointer is a signed integral type underlying it, isn't it?

Edit: I just thought, might it be better to take the arguments as uint64_t maybe?

Upvotes: 2

Views: 321

Answers (1)

Stewart Smith
Stewart Smith

Reputation: 1416

I would not recommend using anything but the declaration provided by the Vulkan header. Casting between pointers and integers is risky and error prone at best, and is definitely not a recommended way of solving something. Especially if it's a macro (it could be anything, even an expression). There are ways to minimize the impact of having to include a large header that would pollute the project.

If you create a "renderer" abstraction and keep the Vulcan header included in source files (single translation unit per include) or headers that are only used in the implementation of the renderer you limit its inclusion to only the translation units where it's necessary.

Upvotes: 2

Related Questions