greenfork / nimraylib_now

The Ultimate Raylib gaming library wrapper for Nim
MIT License
149 stars 16 forks source link

How to wrap callbacks? #67

Open planetis-m opened 2 years ago

planetis-m commented 2 years ago

This is a genuine question at this point, cause I don't have a plan :P

greenfork commented 2 years ago

There's an example of using a C callback function from Nim, does it help? https://github.com/greenfork/nimraylib_now/blob/master/examples/core/core_custom_logging.nim

planetis-m commented 2 years ago

I used vsprintf to a buffer and added an extra function pointer:

type
  TraceLogCallback* = proc (logLevel: TraceLogLevel; text: string) {.nimcall.} ## Logging: Redirect trace log messages

var
  traceLog: TraceLogCallback # TraceLog callback function pointer

proc wrapTraceLogCallback(logLevel: int32; text: cstring; args: va_list) {.cdecl.} =
  var buf = newString(128)
  vsprintf(buf.cstring, text, args)
  traceLog(logLevel.TraceLogLevel, buf)

proc setTraceLogCallback*(callback: TraceLogCallback) =
  ## Set custom trace log
  traceLog = callback
  setTraceLogCallbackImpl(wrapTraceLogCallback)

Not sure if it's worth it. Your opinion?

greenfork commented 2 years ago

There's still va_list type from C varargs. I'm not sure that we want it because if we choose to change it, we make it Nim-native implementation. Here we still have to interface with C. And I'm not sure if we can safely translate it to Nim either.