[Multimedia] Fix ASAN crash issue (#5699)
[platform/core/csapi/tizenfx.git] / src / Tizen.Content.MediaContent / Tizen.Content.MediaContent / InteropHelper.cs
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 using System;
18 using System.Runtime.InteropServices;
19
20 namespace Tizen.Content.MediaContent
21 {
22     internal static class InteropHelper
23     {
24         internal delegate MediaContentError GetStringFunc<T>(T handle, out IntPtr value);
25
26         internal static string GetString<T>(T handle, GetStringFunc<T> func, bool nullable = false)
27         {
28             IntPtr val = IntPtr.Zero;
29             try
30             {
31                 func(handle, out val).ThrowIfError("Failed to get value");
32
33                 if (val == IntPtr.Zero)
34                 {
35                     return nullable ? null : string.Empty;
36                 }
37
38                 return Marshal.PtrToStringAnsi(val);
39             }
40             finally
41             {
42                 Marshal.FreeHGlobal(val);
43             }
44         }
45
46         internal delegate MediaContentError GetValueFunc<T, TValue>(T handle, out TValue value);
47
48         internal static TValue GetValue<T, TValue>(T handle, GetValueFunc<T, TValue> func)
49         {
50             func(handle, out var val).ThrowIfError("Failed to get value");
51
52             return val;
53         }
54
55         internal static TValue GetValue<TValue>(IntPtr handle, GetValueFunc<IntPtr, TValue> func)
56         {
57             func(handle, out var val).ThrowIfError("Failed to get value");
58
59             return val;
60         }
61
62         internal static TValue GetValue<TValue>(Interop.MediaInfoHandle handle,
63             GetValueFunc<Interop.MediaInfoHandle, TValue> func)
64         {
65             func(handle, out var val).ThrowIfError("Failed to get value");
66
67             return val;
68         }
69
70         internal static DateTimeOffset GetDateTime<T>(T handle,
71             GetValueFunc<T, IntPtr> func)
72         {
73             IntPtr time = IntPtr.Zero;
74
75             func(handle, out time).ThrowIfError("Failed to get value");
76
77             return DateTimeOffset.FromUnixTimeSeconds(time.ToInt64());
78         }
79     }
80 }