tinitializers.nim 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. discard """
  2. cmd: "nim cpp $file"
  3. """
  4. {.emit:"""/*TYPESECTION*/
  5. struct CppStruct {
  6. CppStruct(int x, char* y): x(x), y(y){}
  7. void doSomething() {}
  8. int x;
  9. char* y;
  10. };
  11. """.}
  12. type
  13. CppStruct {.importcpp, inheritable.} = object
  14. ChildStruct = object of CppStruct
  15. HasCppStruct = object
  16. cppstruct: CppStruct
  17. proc constructCppStruct(a:cint = 5, b:cstring = "hello"): CppStruct {.importcpp: "CppStruct(@)", constructor.}
  18. proc doSomething(this: CppStruct) {.importcpp.}
  19. proc returnCppStruct(): CppStruct = discard
  20. proc initChildStruct: ChildStruct = ChildStruct()
  21. proc makeChildStruct(): ChildStruct {.constructor:"""ChildStruct(): CppStruct(5, "10")""".} = discard
  22. proc initHasCppStruct(x: cint): HasCppStruct =
  23. HasCppStruct(cppstruct: constructCppStruct(x))
  24. proc main =
  25. var hasCppStruct = initHasCppStruct(2) #generates cppstruct = { 10 } inside the struct
  26. hasCppStruct.cppstruct.doSomething()
  27. discard returnCppStruct() #generates result = { 10 }
  28. discard initChildStruct() #generates ChildStruct temp ({}) bypassed with makeChildStruct
  29. (proc (s:CppStruct) = discard)(CppStruct()) #CppStruct temp ({10})
  30. main()
  31. #Should handle ObjectCalls
  32. {.emit:"""/*TYPESECTION*/
  33. struct Foo {
  34. };
  35. struct Boo {
  36. Boo(int x, char* y, Foo f): x(x), y(y), foo(f){}
  37. int x;
  38. char* y;
  39. Foo foo;
  40. };
  41. """.}
  42. type
  43. Foo {.importcpp, inheritable, bycopy.} = object
  44. Boo {.importcpp, inheritable.} = object
  45. x: int32
  46. y: cstring
  47. foo: Foo
  48. proc makeBoo(a:cint = 10, b:cstring = "hello", foo: Foo = Foo()): Boo {.importcpp, constructor.}
  49. proc main2() =
  50. let cppStruct = makeBoo()
  51. (proc (s:Boo) = discard)(Boo())
  52. main2()