mevalffi.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # re-enable for windows once libffi can be installed in koch.nim
  2. # With win32 (not yet win64), libffi on windows works and this test passes.
  3. when defined(linux) or defined(bsd):
  4. {.passL: "-lm".} # for exp
  5. proc c_exp(a: float64): float64 {.importc: "exp", header: "<math.h>".}
  6. proc c_printf(frmt: cstring): cint {.importc: "printf", header: "<stdio.h>", varargs, discardable.}
  7. const snprintfName = when defined(windows): "_snprintf" else: "snprintf"
  8. proc c_snprintf*(str: cstring, size: csize_t, format: cstring): cint {.importc: snprintfName, header: "<stdio.h>", varargs .}
  9. proc c_malloc(size: csize_t): pointer {.importc:"malloc", header: "<stdlib.h>".}
  10. proc c_free(p: pointer) {.importc:"free", header: "<stdlib.h>".}
  11. proc fun() =
  12. block: # c_exp
  13. var x = 0.3
  14. let b = c_exp(x)
  15. let b2 = int(b*1_000_000) # avoids floating point equality
  16. doAssert b2 == 1349858
  17. doAssert c_exp(0.3) == c_exp(x)
  18. const x2 = 0.3
  19. doAssert c_exp(x2) == c_exp(x)
  20. block: # c_printf
  21. c_printf("foo\n")
  22. c_printf("foo:%d\n", 100)
  23. c_printf("foo:%d\n", 101.cint)
  24. c_printf("foo:%d:%d\n", 102.cint, 103.cint)
  25. let temp = 104.cint
  26. c_printf("foo:%d:%d:%d\n", 102.cint, 103.cint, temp)
  27. var temp2 = 105.cint
  28. c_printf("foo:%g:%s:%d:%d\n", 0.03, "asdf", 103.cint, temp2)
  29. block: # c_snprintf, c_malloc, c_free
  30. let n: uint = 50
  31. var buffer2 = cstring(cast[ptr char](c_malloc(n)))
  32. var s: cstring = "foobar"
  33. var age: cint = 25
  34. let num = c_snprintf(buffer2, n, "s1:%s s2:%s age:%d pi:%g", s, s, age, 3.14)
  35. let numExp = 34
  36. doAssert num == numExp
  37. c_printf("ret=[%s]\n", buffer2)
  38. c_free(buffer2)
  39. block: # c_printf bug
  40. var a = 123
  41. var a2 = a.addr
  42. #[
  43. bug: different behavior between CT RT in this case:
  44. at CT, shows foo2:a=123
  45. at RT, shows foo2:a=<address as int>
  46. ]#
  47. if false:
  48. c_printf("foo2:a=%d\n", a2)
  49. static:
  50. fun()
  51. fun()
  52. when not defined nimEvalffiStderrWorkaround:
  53. import system/ansi_c
  54. block:
  55. proc fun2()=
  56. c_fprintf(cstderr, "hello world stderr\n")
  57. write(stderr, "hi stderr\n")
  58. static: fun2()
  59. fun2()