File: ctypes-unicode.patch

package info (click to toggle)
python-nxs 4.4.1-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 888 kB
  • sloc: python: 2,752; makefile: 152; sh: 10
file content (231 lines) | stat: -rw-r--r-- 10,111 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
Description: Fix handling of str/bytes through ctypes
 libNeXus uses bytes for all the c_char types not Python strings. The
 encoding/decoding interface is defined as the call into the CDLL, that
 is everything in Python code is in strings, except for the immediate
 call into the CDLL. Encoding to bytes / decoding from bytes is done
 via a specified encoding, defaulting to UTF-8.
Author: Stuart Prescott <stuart@debian.org>
--- a/nxs/napi.py
+++ b/nxs/napi.py
@@ -310,7 +310,7 @@
     # ==== File ====
     nxlib.nxiopen_.restype = c_int
     nxlib.nxiopen_.argtypes = [c_char_p, c_int, c_void_pp]
-    def __init__(self, filename, mode='r'):
+    def __init__(self, filename, mode='r', encoding='UTF-8'):
         """
         Open the NeXus file returning a handle.
 
@@ -336,17 +336,19 @@
         if mode not in _nxopen_mode.values():
             raise ValueError("Invalid open mode %s" % str(mode))
 
-        self.filename, self.mode = filename, mode
+        self.encoding = encoding
+        self.filename = self._str2bytes(filename)
+        self.mode = mode
         self.handle = c_void_p(None)
         self._path = []
         self._indata = False
-        status = nxlib.nxiopen_(filename,mode,_ref(self.handle))
+        status = nxlib.nxiopen_(self.filename,mode,_ref(self.handle))
         if status == ERROR:
             if mode in [ACC_READ, ACC_RDWR]:
                 op = 'open'
             else:
                 op = 'create'
-            raise NeXusError("Could not %s %s" % (op,filename))
+            raise NeXusError("Could not %s %s" % (op,self.filename))
         self.isopen = True
 
     def _getpath(self):
@@ -360,6 +362,16 @@
     longpath = property(_getlongpath, doc="Unix-style path including " \
                         + "nxclass to the node")
 
+    def _str2bytes(self, s):
+        if isinstance(s, str):
+            s = s.encode(self.encoding)
+        return s
+
+    def _bytes2str(self, b):
+        if isinstance(b, bytes):
+            b = b.decode(self.encoding)
+        return b
+
     def __del__(self):
         """
         Be sure to close the file before deleting the last reference.
@@ -438,7 +450,7 @@
         Corresponds to NXsetnumberformat(&handle,type,format)
         """
         type = _nxtype_code[type]
-        status = nxlib.nxisetnumberformat_(self.handle,type,format)
+        status = nxlib.nxisetnumberformat_(self.handle,type,self._str2bytes(format))
         if status == ERROR:
             raise ValueError("Could not set %s to %s in %s" %
                              (type, format, self.filename))
@@ -455,7 +467,8 @@
         Corresponds to NXmakegroup(handle, name, nxclass)
         """
         # print("makegroup", self._loc(), name, nxclass)
-        status = nxlib.nximakegroup_(self.handle, name, nxclass)
+        status = nxlib.nximakegroup_(self.handle, self._str2bytes(name),
+                                     self._str2bytes(nxclass))
         if status == ERROR:
             raise NeXusError("Could not create %s:%s in %s" %
                              (nxclass, name, self._loc()))
@@ -476,7 +489,7 @@
 
         Corresponds to NXopenpath(handle, path)
         """
-        self._openpath(path, opendata=True)
+        self._openpath(self._str2bytes(path), opendata=True)
 
     def _openpath(self, path, opendata=True):
         """helper function: open relative path and maybe data"""
@@ -579,7 +592,7 @@
 
         Corresponds to NXopengrouppath(handle, path)
         """
-        self._openpath(path,opendata=False)
+        self._openpath(self._str2bytes(path),opendata=False)
 
     nxlib.nxiopengroup_.restype = c_int
     nxlib.nxiopengroup_.argtypes = [c_void_p, c_char_p, c_char_p]
@@ -595,7 +608,8 @@
         # print("opengroup", self._loc(), name, nxclass)
         if nxclass is None:
             nxclass = self.__getnxclass(name)
-        status = nxlib.nxiopengroup_(self.handle, name, nxclass)
+        status = nxlib.nxiopengroup_(self.handle, self._str2bytes(name),
+                                     self._str2bytes(nxclass))
         if status == ERROR:
             raise ValueError("Could not open %s:%s in %s" %
                              (nxclass, name, self._loc()))
@@ -639,6 +653,8 @@
         nxclass = ctypes.create_string_buffer(MAXNAMELEN)
         n = c_int(0)
         status = nxlib.nxigetgroupinfo_(self.handle,_ref(n),path,nxclass)
+        path = self._bytes2str(path)
+        nxclass = self._bytes2str(nxclass)
         if status == ERROR:
             raise ValueError("Could not get group info: %s" % (self._loc()))
         # print("getgroupinfo", self._loc(), nxclass.value, name.value, n.value)
@@ -692,7 +708,7 @@
         # if nxclass == 'SDS':
         #     dtype = _pytype_code(storage.value)
         # print("nextentry", nxclass.value, name.value, storage.value)
-        return name.value,nxclass.value
+        return self._bytes2str(name.value), self._bytes2str(nxclass.value)
 
     def getentries(self):
         """
@@ -848,7 +864,7 @@
         if self._indata:
             status = ERROR
         else:
-            status = nxlib.nxiopendata_(self.handle, name)
+            status = nxlib.nxiopendata_(self.handle, self._str2bytes(name))
         if status == ERROR:
             raise ValueError("Could not open data %s: %s" % (name, self._loc()))
         self._path.append((name,"SDS"))
@@ -893,7 +909,7 @@
         # print("makedata", self._loc(), name, shape, dtype)
         storage = _nxtype_code[str(dtype)]
         shape = numpy.asarray(shape,'int64')
-        status = nxlib.nximakedata64_(self.handle,name,storage,len(shape),
+        status = nxlib.nximakedata64_(self.handle,self._str2bytes(name),storage,len(shape),
                                       shape.ctypes.data_as(c_int64_p))
         if status == ERROR:
             raise ValueError("Could not create data %s: %s" %
@@ -927,7 +943,9 @@
             chunks[-1] = shape[-1]
         else:
             chunks = numpy.array(chunks,'int64')
-        status = nxlib.nxicompmakedata64_(self.handle,name,storage,len(dims),
+        status = nxlib.nxicompmakedata64_(self.handle,
+                                          self._str2bytes(name),
+                                          storage,len(dims),
                                           dims.ctypes.data_as(c_int64_p),
                                           _compression_code[mode],
                                           chunks.ctypes.data_as(c_int64_p))
@@ -1092,7 +1110,7 @@
             raise NeXusError("Could not get next attr: %s" % (self._loc()))
         dtype = _pytype_code[storage.value]
         # print("getnextattr", name.value, length.value, dtype)
-        return name.value, length.value, dtype
+        return self._bytes2str(name.value), length.value, dtype
 
     # TODO: Resolve discrepency between NeXus API documentation and
     # TODO: apparent behaviour for getattr/putattr length.
@@ -1111,7 +1129,8 @@
         storage = c_int(_nxtype_code[str(dtype)])
         # print("getattr", self._loc(), name, length, size, dtype)
         size = c_int(size)
-        status = nxlib.nxigetattr_(self.handle,name,pdata,_ref(size),_ref(storage))
+        status = nxlib.nxigetattr_(self.handle,self._str2bytes(name),
+                                   pdata,_ref(size),_ref(storage))
         if status == ERROR:
             raise ValueError("Could not read attr %s: %s" % (name, self._loc()))
         # print("getattr", self._loc(), name, datafn())
@@ -1163,7 +1182,8 @@
 
         # Perform the call
         storage = c_int(_nxtype_code[dtype])
-        status = nxlib.nxiputattr_(self.handle,name,data,length,storage)
+        status = nxlib.nxiputattr_(self.handle,self._str2bytes(name),
+                                   data,length,storage)
         if status == ERROR:
             raise NeXusError("Could not write attr %s: %s" %
                              (name, self._loc()))
@@ -1258,7 +1278,8 @@
 
         Corresponds to NXmakenamedlink(handle,name,&ID)
         """
-        status = nxlib.nximakenamedlink_(self.handle,name,_ref(ID))
+        status = nxlib.nximakenamedlink_(self.handle,self._str2bytes(name),
+                                         _ref(ID))
         if status == ERROR:
             raise NeXusError("Could not make link %s: %s" % (name, self._loc()))
 
@@ -1333,7 +1354,7 @@
         status = nxlib.nxiinquirefile_(self.handle,filename,maxnamelen)
         if status == ERROR:
             raise NeXusError("Could not determine filename: %s" % (self._loc()))
-        return filename.value
+        return self._bytes2str(filename.value)
 
     nxlib.nxilinkexternal_.restype = c_int
     nxlib.nxilinkexternal_.argtyps = [c_void_p, c_char_p,
@@ -1347,7 +1368,10 @@
 
         Corresponds to NXisexternalgroup(&handle,name,nxclass,file,len)
         """
-        status = nxlib.nxilinkexternal_(self.handle,name,nxclass,url)
+        status = nxlib.nxilinkexternal_(self.handle,
+                                        self._str2bytes(name),
+                                        self._str2bytes(nxclass),
+                                        self._str2bytes(url))
         if status == ERROR:
             raise NeXusError("Could not link %s to %s: %s" %
                              (name, url, self._loc()))
@@ -1363,12 +1387,15 @@
         Corresponds to NXisexternalgroup(&handle,name,nxclass,file,len)
         """
         url = ctypes.create_string_buffer(maxnamelen)
-        status = nxlib.nxiisexternalgroup_(self.handle,name,nxclass,
-                                              url,maxnamelen)
+        status = nxlib.nxiisexternalgroup_(self.handle,
+                                           self._str2bytes(name),
+                                           self._str2bytes(nxclass),
+                                           url,
+                                           maxnamelen)
         if status == ERROR:
             return None
         else:
-            return url.value
+            return self._bytes2str(url.value)
 
     # ==== Utility functions ====
     def _loc(self):