Hello,
I apologize if I'm doing something totally wrong here, but hopefully someone can point me in the right direction. I have an application in which I would like to pass a pointer to a mutable object into and allow it to be changed by another set of procedures.
A brief mocked up example would be like below:
type
thing = object
text: string
proc show(obj: ptr thing): ptr thing =
return obj
proc change(obj: var ptr thing) =
obj.text = "Goodbye World!"
var x = thing()
x.text = "Hello World!"
echo show(addr x).text
change(var addr x)
echo x.text
This results in the error : >nimtest.nim(16, 17) Error: expected type, but got: addr x
Line 16: being the change(var addr x) line
So, my question is: what am I doing wrong? Is what I am attempting even possible? I've tried a few different approached, even reading the forums here pointing me down a cast[var ptr thing](addr x) route - but that results in an out of memory exception I'd like to do this as one of the procedures down the line updates a sequence of RSS feeds depending on files in a directory if/when they change, last feed id, etc.
Again, apologies if I'm just being an idiot and trying to do something stupid - but I'd be happy to be pointed in the right direction!
Thanks!
First of all - is there a reason you need raw pointers? Typically you can use Nim's own reference type ref that is safe, instead of unsafe ptr which is usually used for low-level code and C FFI.
Anyway, your example can be fixed as follows:
type
thing = object
text: string
proc show(obj: ptr thing): ptr thing =
return obj
proc change(obj: ptr thing) =
obj.text = "Goodbye World!"
var x = thing()
x.text = "Hello World!"
echo show(addr x).text
change(addr x)
echo x.text
Thanks!
No reason to be using raw pointers - I think I was trying to be clever for no reason going down a futile route. I think somewhere in my head thought I was creating multiple copies of an identical object by passing the base Thing = object into procedures and I was trying to prevent that. I think the ref object is actually what I'm after... so I will do some further tests using that knowledge now!
Thanks for setting me off in the, hopefully, right direction now!