29e95f20ffd7dd092428be27ba6d558272a99166
[debian/amanda] / perl / amglue / objwrap.c
1 /*
2  * Copyright (c) 2009 Zmanda, Inc.  All Rights Reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 2 as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11  * for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16  *
17  * Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
18  * Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
19  */
20
21 /* Functions to wrap arbitrary C objects into perl, with a blessing.  These
22  * functions are used when we totally skip SWIG's object-wrapping and build
23  * our own Perl methods to wrap a class -- currently only in AManda::Xfer.
24  */
25
26 #include "amglue.h"
27
28 SV *
29 new_sv_for_c_obj(
30     gpointer c_obj,
31     const char *perl_class)
32 {
33     SV *sv = newSV(0);
34
35     /* Make an SV that contains a pointer to the object, and bless it
36      * with the appropriate class. */
37     sv_setref_pv(sv, perl_class, c_obj);
38
39     return sv;
40 }
41
42 gpointer
43 c_obj_from_sv(
44     SV *sv,
45     const char *derived_from)
46 {
47     SV *referent;
48     IV tmp;
49
50     if (!sv) return NULL;
51     if (!SvOK(sv)) return NULL;
52
53     /* Peel back the layers.  The sv should be a blessed reference to a PV,
54      * and we check the class against derived_from to ensure we have the right
55      * stuff. */
56     if (!sv_isobject(sv) || !sv_derived_from(sv, derived_from)) {
57         croak("Value is not an object of type %s", derived_from);
58         return NULL;
59     }
60
61     referent = (SV *)SvRV(sv);
62     tmp = SvIV(referent);
63     return INT2PTR(gpointer, tmp);
64 }
65