[nim-dev] Can channel send a ref object ?

  • From: e2718e <e2718e@xxxxxxxxx>
  • To: nim-dev@xxxxxxxxxxxxx
  • Date: Mon, 14 Dec 2015 01:09:06 +0000

. code-block:: nimrod
import threadpool

type
AbcImpl = object of RootObj
a* : int
b* : float
c* : string

DefImpl = object of RootObj
d* : string
e* : float
f* : float
g* : int

Abc* = ref AbcImpl
Def* = ref DefImpl

var channel:Channel[tuple[t:string,data:ref RootObj]]

proc recieveMsg() =
let (avai,msg) = channel.tryRecv()
echo repr msg
if avai :
let (t,data) = msg
case t
of "Abc":
echo "Abc\n", repr(data)
of "Def":
echo "Def\n", repr(data)
else:
echo "else\n", repr(data)

proc sendMsg() =
var abc = new(Abc)
abc.a = 1
abc.b = 2.0
abc.c = "cccc"
channel.send((t:"Abc",data:abc))

proc main() =
channel.open()
spawn sendMsg()
spawn recieveMsg()
sync()
channel.close()

main()

In this example, It could not recieve any useful data.
[Field0 = 000000000077D0A0"Abc",
Field1 = ref 000000000077E050 --> []]

Abc
ref 000000000077E050 --> []
so I modified it like this:

. code-block:: nimrod
var channel:Channel[tuple[t:string,data:ptr RootObj]]

proc sendMsg() =
var abc = new(Abc)
abc.a = 1
abc.b = 2.0
abc.c = "cccc"
channel.send((t:"Abc",data:cast[ptr RootObj](abc)))

I got the data.
Abc
ref 000000000076C050 --> [a = 1,
b = 2.0,
c = 000000000076D050"cccc"]

But I don't know do it like this is GC safe ? And Is "Abc" data in the revieve
proc safe ?

Other related posts: