I'm working on porting over some ray tracing code from a C++ project. So far things have been fine, but they used this library called stb_image.h to load in textures.
I thought I would try to create a wrapper for the single function that is used "stbi_load()"
So far I've got this (filename "stb_image.nim")
# This file is a wrapper of a subset for the "stb_image.h" library that is
# needed for the raytracer
# Required before including the stb_image.h header
{.emit: """
#define STB_IMAGE_IMPLEMENTATION
""".}
# Internal function
proc stbi_load(filename: cstring; x, y, comp: var cint; req_comp: cint): cstring
{.importc: "stbi_load", header: "stb_image.h".}
## External function (the Nim friendly version)
proc stbi_load*(filename: string; x, y, comp: var int; req_comp: int): seq[uint8] =
var
width: cint
height: cint
comp2: cint
pixelData: seq[uint8]
let data = stbi_load(filename.cstring, width, height, comp2, req_comp.cint)
# Set the data
x = width.int
y = width.int
comp = comp2.int
newSeq(pixelData, x * y)
# TODO set the pixelData
return pixelData
I seem to be fine, until I compile and get this:
CC: stb_image
Error: execution of an external compiler program 'gcc -c -w -I/home/ben/bin/Nim/lib -o nimcache/stb_image.o nimcache/stb_image.c' failed with exit code: 1
nimcache/stb_image.c:10:23: fatal error: stb_image.h: No such file or directory
compilation terminated.
I have the stb_image.h file right alongside the nim one. What should I do here?
Also, do you think the return type cstring (for the internal function) is fine? stb_image() returns an unsigned char *. I figured casting it to a seq[uint8] should be fine.
Alright, I got it to work. The trick was three things:
Change the emit to this:
# Required before including the stb_image.h header
{.emit: """
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
""".}
Remove the "header," pragma and add a "noDecl" one:
# Internal Function
proc stbi_load(filename: cstring; x, y, comp: var cint; req_comp: cint): cstring
{.importc: "stbi_load", noDecl.}
Tell the compiler where to look for stb_image.h. In my case that file was right alongside stb_image.nim, so for me it was:
--cincludes:.