Skip to content

Commit

Permalink
fixes nim-lang#22680 Nim zero clear an object inherits C++ imported c…
Browse files Browse the repository at this point in the history
…lass when a proc return it
  • Loading branch information
jmgomez committed Sep 10, 2023
1 parent cd24195 commit 803e95f
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
13 changes: 10 additions & 3 deletions compiler/cgen.nim
Original file line number Diff line number Diff line change
Expand Up @@ -498,10 +498,17 @@ proc resetLoc(p: BProc, loc: var TLoc) =
else:
# array passed as argument decayed into pointer, bug #7332
# so we use getTypeDesc here rather than rdLoc(loc)
if not isOrHasImportedCppType(typ): #bug 22679
let tyDesc = getTypeDesc(p.module, loc.t, descKindFromSymKind mapTypeChooser(loc))
if isOrHasImportedCppType(typ):
if lfIndirect in loc.flags:
#C++ cant be just zeroed. We need to call the ctors
var tmp = getTemp(p, loc.t)
linefmt(p, cpsStmts,"#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
[addrLoc(p.config, loc), addrLoc(p.config, tmp), tyDesc])
else:
linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
[addrLoc(p.config, loc),
getTypeDesc(p.module, loc.t, descKindFromSymKind mapTypeChooser(loc))])
[addrLoc(p.config, loc), tyDesc])

# XXX: We can be extra clever here and call memset only
# on the bytes following the m_type field?
genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
Expand Down
50 changes: 50 additions & 0 deletions tests/cpp/t22680.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
discard """
cmd: "nim cpp $file"
output:'''
cppNZ.x = 123
cppNZInit.x = 123
inheritCpp.x = 123
inheritCppInit.x = 123
inheritCppCtor.x = 123
'''
"""
import std/sugar

{.emit:"""/*TYPESECTION*/
struct CppNonZero {
int x = 123;
};
""".}

type
CppNonZero {.importcpp, inheritable.} = object
x: cint

InheritCpp = object of CppNonZero

proc initCppNonZero: CppNonZero =
CppNonZero()

proc initInheritCpp: InheritCpp =
InheritCpp()

proc ctorInheritCpp: InheritCpp {.constructor.} =
discard

proc main =
var cppNZ: CppNonZero
dump cppNZ.x

var cppNZInit = initCppNonZero()
dump cppNZInit.x

var inheritCpp: InheritCpp
dump inheritCpp.x

var inheritCppInit = initInheritCpp()
dump inheritCppInit.x

var inheritCppCtor = ctorInheritCpp()
dump inheritCppCtor.x

main()

0 comments on commit 803e95f

Please sign in to comment.