Nick Ing-Simmons wrote:
Vladimir Marek <[EMAIL PROTECTED]> writes:

Hello all,

I do have C++ object typemapped into perl class. Then I have two functions which creates and destroys that object

create_object ($obj);
destroy_object ($obj);

first function is easy, I create the object like:
c_obj *x=new c_obj;
sv_setref_pv( ST(0)), CLASS, (void*)x );
SvSETMAGIC(ST(0));

but the destroy_function has to call delete on the object (sometime, in another thread, I can't stop that), but I don't know how to de-mortalize' variable, in order to stop perl to call destructor on it again.


Do you mean mortal in the sv_2mortal() sense?
yes

Avoiding that is easy - all that a "mortal" SV does is an automatic SvREFCNT_dec() on scope exit. So you can de-mortalize by SvREFCNT_inc().
But then the REFCNT counter of the object will not be freed. But yes, this is still better then not freeing whole object. Thank you for tip.

Tk for example is quite like above - when a widget is created its object has SvREFCNT_inc'ed higher than you might expect and $widget->destroy does corresponding SvREFCNT_dec(s).
Then perl calls DESTROY which free()s the memory.
Ah, the point is that perl cannot call destructor of the object.

But this path risks leaks unless you are very sure that destroys get called.
yup

Why are you having destroy_object of your own rather than letting perl track usage and eventually call DESTROY once?
The object is message which is send over network, which can take quite lot of time. So another thread handles the sending, and frees the message when its done.

One solution is to create copy of the object and free that copy, but I would like to do it without copying.
sv_setref_pv() puts the pointer in the SvIV slot.
So you can de-associate the SV from the C++ thing by zeroing the SvIV.
But then destroy_object needs to be prepared to do nothing when passed NULL.
You meen bless integer into the package, and then all functions will convert it back to pointer ? Hmm, never thought about that ... I'm afraid of some automatic conversions or whatever ... but might work.

        Thank you
                Vladimir Marek



Reply via email to