Check if property exists before accessing or setting it
authorStephan Sundermann <stephansundermann@gmail.com>
Thu, 10 Oct 2013 18:26:26 +0000 (20:26 +0200)
committerStephan Sundermann <stephansundermann@gmail.com>
Sat, 21 Dec 2013 15:52:21 +0000 (16:52 +0100)
Previously when accessing/setting a property which does not exist,
there will be segmentation faults

sources/custom/Object.cs

index 43ab287..bd35dff 100644 (file)
 // You should have received a copy of the GNU Affero General Public License
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+using System;
+using System.Runtime.InteropServices;
+
 namespace Gst {
-       using System;
-       using System.Runtime.InteropServices;
 
+       public class PropertyNotFoundException : Exception {}
+       
        partial class Object 
        {
+               [DllImport ("libgobject-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
+               static extern IntPtr g_object_class_find_property (IntPtr klass, IntPtr name);
+
+               bool PropertyExists (string name) {
+                       var ptr = g_object_class_find_property (GType.GetClassPtr (), GLib.Marshaller.StringToPtrGStrdup (name));
+                       var result = ptr != IntPtr.Zero;
+                       GLib.Marshaller.Free (ptr);
+
+                       return result;
+               }
+
                public object this[string property] {
                  get {
-                   GLib.Value v = GetProperty (property);
-                   object o = v.Val;
-                   v.Dispose ();
-                   return o;
+                               if (PropertyExists (property)) {
+                                       GLib.Value v = GetProperty (property);
+                                       object o = v.Val;
+                                       v.Dispose ();
+                                       return o;
+                               } else
+                                       throw new PropertyNotFoundException ();
                  } set {
-                   GLib.Value v = new GLib.Value (this, property);
-                   v.Val = value;
-                   SetProperty (property, v);
-                   v.Dispose ();
+                               if (PropertyExists (property)) {
+                                       GLib.Value v = new GLib.Value (this, property);
+                                       v.Val = value;
+                                       SetProperty (property, v);
+                                       v.Dispose ();
+                               } else
+                                       throw new PropertyNotFoundException ();
                  }
                }