koffi 2.1.0-beta.2 → 2.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/ChangeLog.md +2 -2
  2. package/build/qemu/2.1.0-beta.3/koffi_darwin_arm64.tar.gz +0 -0
  3. package/build/qemu/2.1.0-beta.3/koffi_darwin_x64.tar.gz +0 -0
  4. package/build/qemu/2.1.0-beta.3/koffi_freebsd_arm64.tar.gz +0 -0
  5. package/build/qemu/2.1.0-beta.3/koffi_freebsd_ia32.tar.gz +0 -0
  6. package/build/qemu/2.1.0-beta.3/koffi_freebsd_x64.tar.gz +0 -0
  7. package/build/qemu/2.1.0-beta.3/koffi_linux_arm32hf.tar.gz +0 -0
  8. package/build/qemu/2.1.0-beta.3/koffi_linux_arm64.tar.gz +0 -0
  9. package/build/qemu/2.1.0-beta.3/koffi_linux_ia32.tar.gz +0 -0
  10. package/build/qemu/2.1.0-beta.3/koffi_linux_riscv64hf64.tar.gz +0 -0
  11. package/build/qemu/2.1.0-beta.3/koffi_linux_x64.tar.gz +0 -0
  12. package/build/qemu/2.1.0-beta.3/koffi_openbsd_ia32.tar.gz +0 -0
  13. package/build/qemu/2.1.0-beta.3/koffi_openbsd_x64.tar.gz +0 -0
  14. package/build/qemu/2.1.0-beta.3/koffi_win32_arm64.tar.gz +0 -0
  15. package/build/qemu/2.1.0-beta.3/koffi_win32_ia32.tar.gz +0 -0
  16. package/build/qemu/2.1.0-beta.3/koffi_win32_x64.tar.gz +0 -0
  17. package/doc/Makefile +1 -1
  18. package/doc/conf.py +5 -0
  19. package/doc/dist/doctrees/changes.doctree +0 -0
  20. package/doc/dist/doctrees/environment.pickle +0 -0
  21. package/doc/dist/doctrees/functions.doctree +0 -0
  22. package/doc/dist/doctrees/index.doctree +0 -0
  23. package/doc/dist/doctrees/types.doctree +0 -0
  24. package/doc/dist/html/.buildinfo +4 -0
  25. package/doc/dist/html/_sources/benchmarks.md.txt +137 -0
  26. package/doc/dist/html/_sources/changes.md.txt +161 -0
  27. package/doc/dist/html/_sources/contribute.md.txt +127 -0
  28. package/doc/dist/html/_sources/functions.md.txt +421 -0
  29. package/doc/dist/html/_sources/index.rst.txt +39 -0
  30. package/doc/dist/html/_sources/memory.md.txt +32 -0
  31. package/doc/dist/html/_sources/platforms.md.txt +31 -0
  32. package/doc/dist/html/_sources/start.md.txt +100 -0
  33. package/doc/dist/html/_sources/types.md.txt +541 -0
  34. package/doc/dist/html/_static/_sphinx_javascript_frameworks_compat.js +134 -0
  35. package/doc/dist/html/_static/basic.css +932 -0
  36. package/doc/dist/html/_static/bench_linux.png +0 -0
  37. package/doc/dist/html/_static/bench_windows.png +0 -0
  38. package/doc/dist/html/_static/custom.css +22 -0
  39. package/doc/dist/html/_static/debug.css +69 -0
  40. package/doc/dist/html/_static/doctools.js +264 -0
  41. package/doc/dist/html/_static/documentation_options.js +14 -0
  42. package/doc/dist/html/_static/file.png +0 -0
  43. package/doc/dist/html/_static/jquery-3.6.0.js +10881 -0
  44. package/doc/dist/html/_static/jquery.js +2 -0
  45. package/doc/dist/html/_static/language_data.js +199 -0
  46. package/doc/dist/html/_static/minus.png +0 -0
  47. package/doc/dist/html/_static/perf_linux_20220623.png +0 -0
  48. package/doc/dist/html/_static/perf_linux_20220623_2.png +0 -0
  49. package/doc/dist/html/_static/perf_windows_20220623.png +0 -0
  50. package/doc/dist/html/_static/perf_windows_20220623_2.png +0 -0
  51. package/doc/dist/html/_static/plus.png +0 -0
  52. package/doc/dist/html/_static/pygments.css +252 -0
  53. package/doc/dist/html/_static/scripts/furo-extensions.js +0 -0
  54. package/doc/dist/html/_static/scripts/furo.js +3 -0
  55. package/doc/dist/html/_static/scripts/furo.js.LICENSE.txt +7 -0
  56. package/doc/dist/html/_static/scripts/furo.js.map +1 -0
  57. package/doc/dist/html/_static/searchtools.js +531 -0
  58. package/doc/dist/html/_static/skeleton.css +296 -0
  59. package/doc/dist/html/_static/styles/furo-extensions.css +2 -0
  60. package/doc/dist/html/_static/styles/furo-extensions.css.map +1 -0
  61. package/doc/dist/html/_static/styles/furo.css +2 -0
  62. package/doc/dist/html/_static/styles/furo.css.map +1 -0
  63. package/doc/dist/html/_static/underscore-1.13.1.js +2042 -0
  64. package/doc/dist/html/_static/underscore.js +6 -0
  65. package/doc/dist/html/benchmarks.html +571 -0
  66. package/doc/dist/html/changes.html +686 -0
  67. package/doc/dist/html/contribute.html +403 -0
  68. package/doc/dist/html/functions.html +718 -0
  69. package/doc/dist/html/genindex.html +253 -0
  70. package/doc/dist/html/index.html +359 -0
  71. package/doc/dist/html/memory.html +346 -0
  72. package/doc/dist/html/objects.inv +0 -0
  73. package/doc/dist/html/platforms.html +371 -0
  74. package/doc/dist/html/search.html +261 -0
  75. package/doc/dist/html/searchindex.js +1 -0
  76. package/doc/dist/html/start.html +384 -0
  77. package/doc/dist/html/types.html +1061 -0
  78. package/doc/make.bat +1 -1
  79. package/doc/templates/badges.html +1 -1
  80. package/doc/types.md +2 -0
  81. package/package.json +2 -1
  82. package/src/abi_arm32.cc +142 -200
  83. package/src/abi_arm64.cc +113 -122
  84. package/src/abi_riscv64.cc +76 -92
  85. package/src/abi_x64_sysv.cc +76 -92
  86. package/src/abi_x64_win.cc +76 -92
  87. package/src/abi_x86.cc +128 -164
  88. package/test/misc.c +43 -0
  89. package/test/sync.js +81 -0
  90. package/build/qemu/2.1.0-beta.2/koffi_darwin_arm64.tar.gz +0 -0
  91. package/build/qemu/2.1.0-beta.2/koffi_darwin_x64.tar.gz +0 -0
  92. package/build/qemu/2.1.0-beta.2/koffi_freebsd_arm64.tar.gz +0 -0
  93. package/build/qemu/2.1.0-beta.2/koffi_freebsd_ia32.tar.gz +0 -0
  94. package/build/qemu/2.1.0-beta.2/koffi_freebsd_x64.tar.gz +0 -0
  95. package/build/qemu/2.1.0-beta.2/koffi_linux_arm32hf.tar.gz +0 -0
  96. package/build/qemu/2.1.0-beta.2/koffi_linux_arm64.tar.gz +0 -0
  97. package/build/qemu/2.1.0-beta.2/koffi_linux_ia32.tar.gz +0 -0
  98. package/build/qemu/2.1.0-beta.2/koffi_linux_riscv64hf64.tar.gz +0 -0
  99. package/build/qemu/2.1.0-beta.2/koffi_linux_x64.tar.gz +0 -0
  100. package/build/qemu/2.1.0-beta.2/koffi_openbsd_ia32.tar.gz +0 -0
  101. package/build/qemu/2.1.0-beta.2/koffi_openbsd_x64.tar.gz +0 -0
  102. package/build/qemu/2.1.0-beta.2/koffi_win32_arm64.tar.gz +0 -0
  103. package/build/qemu/2.1.0-beta.2/koffi_win32_ia32.tar.gz +0 -0
  104. package/build/qemu/2.1.0-beta.2/koffi_win32_x64.tar.gz +0 -0
@@ -0,0 +1,541 @@
1
+ # Data types
2
+
3
+ ## Primitive types
4
+
5
+ ### Standard types
6
+
7
+ While the C standard allows for variation in the size of most integer types, Koffi enforces the same definition for most primitive types, listed below:
8
+
9
+ JS type | C type | Bytes | Signedness | Note
10
+ ---------------- | ----------------------------- | ----- | ---------- | ---------------------------
11
+ Undefined | void | 0 | | Only valid as a return type
12
+ Number (integer) | int8, int8_t | 1 | Signed |
13
+ Number (integer) | uint8, uint8_t | 1 | Unsigned |
14
+ Number (integer) | char | 1 | Signed |
15
+ Number (integer) | uchar, unsigned char | 1 | Unsigned |
16
+ Number (integer) | char16, char16_t | 2 | Signed |
17
+ Number (integer) | int16, int16_t | 2 | Signed |
18
+ Number (integer) | uint16, uint16_t | 2 | Unsigned |
19
+ Number (integer) | short | 2 | Signed |
20
+ Number (integer) | ushort, unsigned short | 2 | Unsigned |
21
+ Number (integer) | int32, int32_t | 4 | Signed |
22
+ Number (integer) | uint32, uint32_t | 4 | Unsigned |
23
+ Number (integer) | int | 4 | Signed |
24
+ Number (integer) | uint, unsigned int | 4 | Unsigned |
25
+ Number (integer) | int64, int64_t | 8 | Signed |
26
+ Number (integer) | uint64, uint64_t | 8 | Unsigned |
27
+ Number (integer) | longlong, long long | 8 | Signed |
28
+ Number (integer) | ulonglong, unsigned long long | 8 | Unsigned |
29
+ Number (float) | float32 | 4 | |
30
+ Number (float) | float64 | 8 | |
31
+ Number (float) | float | 4 | |
32
+ Number (float) | double | 8 | |
33
+
34
+ Koffi also accepts BigInt values when converting from JS to C integers. If the value exceeds the range of the C type, Koffi will convert the number to an undefined value. In the reverse direction, BigInt values are automatically used when needed for big 64-bit integers.
35
+
36
+ Koffi defines a few more types that can change size depending on the OS and the architecture:
37
+
38
+ JS type | C type | Signedness | Note
39
+ ---------------- | ---------------- | ---------- | ------------------------------------------------
40
+ Boolean | bool | | Usually one byte
41
+ Number (integer) | long | Signed | 4 or 8 bytes depending on platform (LP64, LLP64)
42
+ Number (integer) | ulong | Unsigned | 4 or 8 bytes depending on platform (LP64, LLP64)
43
+ Number (integer) | unsigned long | Unsigned | 4 or 8 bytes depending on platform (LP64, LLP64)
44
+ Number (integer) | intptr | Signed | 4 or 8 bytes depending on register width
45
+ Number (integer) | intptr_t | Signed | 4 or 8 bytes depending on register width
46
+ Number (integer) | uintptr | Unsigned | 4 or 8 bytes depending on register width
47
+ Number (integer) | uintptr_t | Unsigned | 4 or 8 bytes depending on register width
48
+ String | str, string | | JS strings are converted to and from UTF-8
49
+ String | str16, string16 | | JS strings are converted to and from UTF-16 (LE)
50
+
51
+ Primitive types can be specified by name (in a string) or through `koffi.types`:
52
+
53
+ ```js
54
+ // These two lines do the same:
55
+ let struct1 = koffi.struct({ dummy: 'long' });
56
+ let struct2 = koffi.struct({ dummy: koffi.types.long });
57
+ ```
58
+
59
+ ### Endian-sensitive types
60
+
61
+ Koffi defines a bunch of endian-sensitive types, which can be used when dealing with binary data (network payloads, binary file formats, etc.).
62
+
63
+ JS type | C type | Bytes | Signedness | Endianness
64
+ ---------------- | ---------------------- | ----- | ---------- | -------------
65
+ Number (integer) | int16_le, int16_le_t | 2 | Signed | Little Endian
66
+ Number (integer) | int16_be, int16_be_t | 2 | Signed | Big Endian
67
+ Number (integer) | uint16_le, uint16_le_t | 2 | Unsigned | Little Endian
68
+ Number (integer) | uint16_be, uint16_be_t | 2 | Unsigned | Big Endian
69
+ Number (integer) | int32_le, int32_le_t | 4 | Signed | Little Endian
70
+ Number (integer) | int32_be, int32_be_t | 4 | Signed | Big Endian
71
+ Number (integer) | uint32_le, uint32_le_t | 4 | Unsigned | Little Endian
72
+ Number (integer) | uint32_be, uint32_be_t | 4 | Unsigned | Big Endian
73
+ Number (integer) | int64_le, int64_le_t | 8 | Signed | Little Endian
74
+ Number (integer) | int64_be, int64_be_t | 8 | Signed | Big Endian
75
+ Number (integer) | uint64_le, uint64_le_t | 8 | Unsigned | Little Endian
76
+ Number (integer) | uint64_be, uint64_be_t | 8 | Unsigned | Big Endian
77
+
78
+ ## Struct types
79
+
80
+ ### Struct definition
81
+
82
+ Koffi converts JS objects to C structs, and vice-versa.
83
+
84
+ Unlike function declarations, as of now there is only one way to create a struct type, with the `koffi.struct()` function. This function takes two arguments: the first one is the name of the type, and the second one is an object containing the struct member names and types. You can omit the first argument to declare an anonymous struct.
85
+
86
+ The following example illustrates how to declare the same struct in C and in JS with Koffi:
87
+
88
+ ```c
89
+ typedef struct A {
90
+ int a;
91
+ char b;
92
+ const char *c;
93
+ struct {
94
+ double d1;
95
+ double d2;
96
+ } d;
97
+ } A;
98
+ ```
99
+
100
+ ```js
101
+ const A = koffi.struct('A', {
102
+ a: 'int',
103
+ b: 'char',
104
+ c: 'const char *', // Koffi does not care about const, it is ignored
105
+ d: koffi.struct({
106
+ d1: 'double',
107
+ d2: 'double'
108
+ })
109
+ });
110
+ ```
111
+
112
+ Koffi follows the C and ABI rules regarding struct alignment and padding.
113
+
114
+ Once a struct is declared, you can use it by name (with a string, like you can do for primitive types) or through the value returned by the call to `koffi.struct()`. Only the latter is possible when declaring an anonymous struct.
115
+
116
+ ```js
117
+ // The following two function declarations are equivalent, and declare a function taking an A value and returning A
118
+ const Function1 = lib.func('A Function(A value)');
119
+ const Function2 = lib.func('Function', A, [A]);
120
+ ```
121
+
122
+ Koffi automatically follows the platform C ABI regarding alignment and padding. However, you can override these rules if needed with:
123
+
124
+ - Pack all members without padding with `koffi.pack()` (instead of `koffi.struct()`)
125
+ - Change alignment of a specific member as shown below
126
+
127
+ ```js
128
+ // This struct is 3 bytes long
129
+ const PackedStruct = koffi.pack('PackedStruct', {
130
+ a: 'int8_t',
131
+ b: 'int16_t'
132
+ });
133
+
134
+ // This one is 18 bytes long, the second member has an alignment requirement of 16 bytes
135
+ const BigStruct = koffi.struct('BigStruct', {
136
+ a: 'int8_t',
137
+ b: [16, 'int16_t']
138
+ })
139
+ ```
140
+
141
+ ### Opaque types
142
+
143
+ Many C libraries use some kind of object-oriented API, with a pair of functions dedicated to create and delete objects. An obvious example of this can be found in stdio.h, with the opaque `FILE *` pointer. You can open and close files with `fopen()` and `fclose()`, and manipule the opaque pointer with other functions such as `fread()` or `ftell()`.
144
+
145
+ In Koffi, you can manage this with opaque types. Declare the opaque type with `koffi.opaque(name)`, and use a pointer to this type either as a return type or some kind of [output parameter](functions.md#output-parameters) (with a double pointer).
146
+
147
+ ```{note}
148
+ Opaque types **have changed in version 2.0, and again in version 2.1**.
149
+
150
+ In Koffi 1.x, opaque handles were defined in a way that made them usable directly as parameter and return types, obscuring the underlying pointer.
151
+
152
+ Now, you must use them through a pointer, and use an array for output parameters. This is shown in the example below (look for the call to `ConcatNewOut` in the JS part), and is described in the section on [output parameters](functions.md#output-parameters).
153
+
154
+ In addition to this, you should use `koffi.opaque()` (introduced in Koffi 2.1) instead of `koffi.handle()` which is deprecated, and will be removed eventually in Koffi 3.0.
155
+
156
+ Consult the [migration guide](changes.md) for more information.
157
+ ```
158
+
159
+ The full example below implements an iterative string builder (concatenator) in C, and uses it from Javascript to output a mix of Hello World and FizzBuzz. The builder is hidden behind an opaque type, and is created and destroyed using a pair of C functions: `ConcatNew` (or `ConcatNewOut`) and `ConcatFree`.
160
+
161
+ ```c
162
+ // Build with: clang -fPIC -o handles.so -shared handles.c -Wall -O2
163
+
164
+ #include <stdlib.h>
165
+ #include <stdbool.h>
166
+ #include <stdio.h>
167
+ #include <errno.h>
168
+ #include <string.h>
169
+
170
+ typedef struct Fragment {
171
+ struct Fragment *next;
172
+
173
+ size_t len;
174
+ char str[];
175
+ } Fragment;
176
+
177
+ typedef struct Concat {
178
+ Fragment *first;
179
+ Fragment *last;
180
+
181
+ size_t total;
182
+ } Concat;
183
+
184
+ bool ConcatNewOut(Concat **out)
185
+ {
186
+ Concat *c = malloc(sizeof(*c));
187
+ if (!c) {
188
+ fprintf(stderr, "Failed to allocate memory: %s\n", strerror(errno));
189
+ return false;
190
+ }
191
+
192
+ c->first = NULL;
193
+ c->last = NULL;
194
+ c->total = 0;
195
+
196
+ *out = c;
197
+ return true;
198
+ }
199
+
200
+ Concat *ConcatNew()
201
+ {
202
+ Concat *c = NULL;
203
+ ConcatNewOut(&c);
204
+ return c;
205
+ }
206
+
207
+ void ConcatFree(Concat *c)
208
+ {
209
+ if (!c)
210
+ return;
211
+
212
+ Fragment *f = c->first;
213
+
214
+ while (f) {
215
+ Fragment *next = f->next;
216
+ free(f);
217
+ f = next;
218
+ }
219
+
220
+ free(c);
221
+ }
222
+
223
+ bool ConcatAppend(Concat *c, const char *frag)
224
+ {
225
+ size_t len = strlen(frag);
226
+
227
+ Fragment *f = malloc(sizeof(*f) + len + 1);
228
+ if (!f) {
229
+ fprintf(stderr, "Failed to allocate memory: %s\n", strerror(errno));
230
+ return false;
231
+ }
232
+
233
+ f->next = NULL;
234
+ if (c->last) {
235
+ c->last->next = f;
236
+ } else {
237
+ c->first = f;
238
+ }
239
+ c->last = f;
240
+ c->total += len;
241
+
242
+ f->len = len;
243
+ memcpy(f->str, frag, len);
244
+ f->str[len] = 0;
245
+
246
+ return true;
247
+ }
248
+
249
+ const char *ConcatBuild(Concat *c)
250
+ {
251
+ Fragment *r = malloc(sizeof(*r) + c->total + 1);
252
+ if (!r) {
253
+ fprintf(stderr, "Failed to allocate memory: %s\n", strerror(errno));
254
+ return NULL;
255
+ }
256
+
257
+ r->next = NULL;
258
+ r->len = 0;
259
+
260
+ Fragment *f = c->first;
261
+
262
+ while (f) {
263
+ Fragment *next = f->next;
264
+
265
+ memcpy(r->str + r->len, f->str, f->len);
266
+ r->len += f->len;
267
+
268
+ free(f);
269
+ f = next;
270
+ }
271
+ r->str[r->len] = 0;
272
+
273
+ c->first = r;
274
+ c->last = r;
275
+
276
+ return r->str;
277
+ }
278
+ ```
279
+
280
+ ```js
281
+ const koffi = require('koffi');
282
+ const lib = koffi.load('./handles.so');
283
+
284
+ const Concat = koffi.opaque('Concat');
285
+ const ConcatNewOut = lib.func('bool ConcatNewOut(_Out_ Concat **out)');
286
+ const ConcatNew = lib.func('Concat *ConcatNew()');
287
+ const ConcatFree = lib.func('void ConcatFree(Concat *c)');
288
+ const ConcatAppend = lib.func('bool ConcatAppend(Concat *c, const char *frag)');
289
+ const ConcatBuild = lib.func('const char *ConcatBuild(Concat *c)');
290
+
291
+ let c = ConcatNew();
292
+ if (!c) {
293
+ // This is stupid, it does the same, but try both versions (return value, output parameter)
294
+ let ptr = [null];
295
+ if (!ConcatNewOut(ptr))
296
+ throw new Error('Allocation failure');
297
+ c = ptr[0];
298
+ }
299
+
300
+ try {
301
+ if (!ConcatAppend(c, 'Hello... '))
302
+ throw new Error('Allocation failure');
303
+ if (!ConcatAppend(c, 'World!\n'))
304
+ throw new Error('Allocation failure');
305
+
306
+ for (let i = 1; i <= 30; i++) {
307
+ let frag;
308
+ if (i % 15 == 0) {
309
+ frag = 'FizzBuzz';
310
+ } else if (i % 5 == 0) {
311
+ frag = 'Buzz';
312
+ } else if (i % 3 == 0) {
313
+ frag = 'Fizz';
314
+ } else {
315
+ frag = String(i);
316
+ }
317
+
318
+ if (!ConcatAppend(c, frag))
319
+ throw new Error('Allocation failure');
320
+ if (!ConcatAppend(c, ' '))
321
+ throw new Error('Allocation failure');
322
+ }
323
+
324
+ let str = ConcatBuild(c);
325
+ if (str == null)
326
+ throw new Error('Allocation failure');
327
+ console.log(str);
328
+ } finally {
329
+ ConcatFree(c);
330
+ }
331
+ ```
332
+
333
+ ## Pointer types
334
+
335
+ In C, pointer arguments are used for differenty purposes. It is important to distinguish these use cases because Koffi provides different ways to deal with each of them:
336
+
337
+ - **Struct pointers**: Use of struct pointers by C libraries fall in two cases: avoid (potentially) expensive copies, and to let the function change struct contents (output or input/output arguments).
338
+ - **Opaque pointers**: the library does not expose the contents of the structs, and only provides you with a pointer to it (e.g. `FILE *`). Only the functions provided by the library can do something with this pointer, in Koffi we call this an opaque type. This is usually done for ABI-stability reason, and to prevent library users from messing directly with library internals.
339
+ - **Pointers to primitive types**: This is more rare, and generally used for output or input/output arguments. The Win32 API has a lot of these.
340
+ - **Arrays**: in C, you dynamically-sized arrays are usually passed to functions with pointers, either NULL-terminated (or any other sentinel value) or with an additional length argument.
341
+
342
+ ### Struct pointers
343
+
344
+ The following Win32 example uses `GetCursorPos()` (with an output parameter) to retrieve and show the current cursor position.
345
+
346
+ ```js
347
+ const koffi = require('koffi');
348
+ const lib = koffi.load('kernel32.dll');
349
+
350
+ // Type declarations
351
+ const POINT = koffi.struct('POINT', {
352
+ x: 'long',
353
+ y: 'long'
354
+ });
355
+
356
+ // Functions declarations
357
+ const GetCursorPos = lib.func('int __stdcall GetCursorPos(_Out_ POINT *pos)');
358
+
359
+ // Get and show cursor position
360
+ let pos = {};
361
+ if (!GetCursorPos(pos))
362
+ throw new Error('Failed to get cursor position');
363
+ console.log(pos);
364
+ ```
365
+
366
+ ### Named pointer types
367
+
368
+ *New in Koffi 2.0*
369
+
370
+ Some C libraries use handles, which behave as pointers to opaque structs. An example of this is the HANDLE type in the Win32 API. If you want to reproduce this behavior, you can define a **named pointer type** to an opaque type, like so:
371
+
372
+ ```js
373
+ const HANDLE = koffi.pointer('HANDLE', koffi.opaque());
374
+
375
+ // And now you get to use it this way:
376
+ const GetHandleInformation = lib.func('bool __stdcall GetHandleInformation(HANDLE h, _Out_ uint32_t *flags)');
377
+ const CloseHandle = lib.func('bool __stdcall CloseHandle(HANDLE h)');
378
+ ```
379
+
380
+ ### Pointers to primitive types
381
+
382
+ In javascript, it is not possible to pass a primitive value by reference to another function. This means that you cannot call a function and expect it to modify the value of one of its number or string parameter.
383
+
384
+ However, arrays and objects (among others) are reference type values. Assigning an array or an object from one variable to another does not invole any copy. Instead, as the following example illustrates, the new variable references the same array as the first:
385
+
386
+ ```js
387
+ let list1 = [1, 2];
388
+ let list2 = list1;
389
+
390
+ list2[1] = 42;
391
+
392
+ console.log(list1); // Prints [1, 42]
393
+ ```
394
+
395
+ All of this means that C functions that are expected to modify their primitive output values (such as an `int *` parameter) cannot be used directly. However, thanks to Koffi's transparent array support, you can use Javascript arrays to approximate reference semantics with single-element arrays.
396
+
397
+ Below, you can find an example of an addition function where the result is stored in an `int *` input/output parameter and how to use this function from Koffi.
398
+
399
+ ```c
400
+ void AddInt(int *dest, int add)
401
+ {
402
+ *dest += add;
403
+ }
404
+ ```
405
+
406
+ You can simply pass a single-element array as the first argument:
407
+
408
+ ```js
409
+ const AddInt = lib.func('void AddInt(_Inout_ int *dest, int add)');
410
+
411
+ let sum = [36];
412
+ AddInt(sum, 6);
413
+
414
+ console.log(sum[0]); // Prints 42
415
+ ```
416
+
417
+ ## Array types
418
+
419
+ ### Fixed-size C arrays
420
+
421
+ Fixed-size arrays are declared with `koffi.array(type, length)`. Just like in C, they cannot be passed as functions parameters (they degenerate to pointers), or returned by value. You can however embed them in struct types.
422
+
423
+ Koffi applies the following conversion rules when passing arrays to/from C:
424
+
425
+ - **JS to C**: Koffi can take a normal Array (e.g. `[1, 2]`) or a TypedArray of the correct type (e.g. `Uint8Array` for an array of `uint8_t` numbers)
426
+ - **C to JS** (return value, output parameters, callbacks): Koffi will use a TypedArray if possible. But you can change this behavior when you create the array type with the optional hint argument: `koffi.array('uint8_t', 64, 'array')`. For non-number types, such as arrays of strings or structs, Koffi creates normal arrays.
427
+
428
+ See the example below:
429
+
430
+ ```js
431
+ const koffi = require('koffi');
432
+
433
+ // Those two structs are exactly the same, only the array conversion hint is different
434
+ const Foo1 = koffi.struct('Foo', {
435
+ i: 'int',
436
+ a16: koffi.array('int16_t', 8)
437
+ });
438
+ const Foo2 = koffi.struct('Foo', {
439
+ i: 'int',
440
+ a16: koffi.array('int16_t', 8, 'array')
441
+ });
442
+
443
+ // Uses an hypothetical C function that just returns the struct passed as a parameter
444
+ const ReturnFoo1 = lib.func('Foo1 ReturnFoo(Foo1 p)');
445
+ const ReturnFoo2 = lib.func('Foo2 ReturnFoo(Foo2 p)');
446
+
447
+ console.log(ReturnFoo1({ i: 5, a16: [6, 8] })) // Prints { i: 5, a16: Int16Array(2) [6, 8] }
448
+ console.log(ReturnFoo2({ i: 5, a16: [6, 8] })) // Prints { i: 5, a16: [6, 8] }
449
+ ```
450
+
451
+ ### Fixed-size string buffers
452
+
453
+ Koffi can also convert JS strings to fixed-sized arrays in the following cases:
454
+
455
+ - **char arrays** are filled with the UTF-8 encoded string, truncated if needed. The buffer is always NUL-terminated.
456
+ - **char16 (or char16_t) arrays** are filled with the UTF-16 encoded string, truncated if needed. The buffer is always NUL-terminated.
457
+
458
+ The reverse case is also true, Koffi can convert a C fixed-size buffer to a JS string. This happens by default for char, char16 and char16_t arrays, but you can also explicitly ask for this with the `string` array hint (e.g. `koffi.array('char', 8, 'string')`).
459
+
460
+ ### Array pointers (dynamic arrays)
461
+
462
+ In C, dynamically-sized arrays are usually passed around as pointers. The length is either passed as an additional argument, or inferred from the array content itself, for example with a terminating sentinel value (such as a NULL pointers in the case of an array of strings).
463
+
464
+ Koffi can translate JS arrays and TypedArrays to pointer arguments. However, because C does not have a proper notion of dynamically-sized arrays (fat pointers), you need to provide the length or the sentinel value yourself depending on the API.
465
+
466
+ Here is a simple example of a C function taking a NULL-terminated list of strings as input, to calculate the total length of all strings.
467
+
468
+ ```c
469
+ // Build with: clang -fPIC -o length.so -shared length.c -Wall -O2
470
+
471
+ #include <stdlib.h>
472
+ #include <stdint.h>
473
+ #include <string.h>
474
+
475
+ int64_t ComputeTotalLength(const char **strings)
476
+ {
477
+ int64_t total = 0;
478
+
479
+ for (const char **ptr = strings; *ptr; ptr++) {
480
+ const char *str = *ptr;
481
+ total += strlen(str);
482
+ }
483
+
484
+ return total;
485
+ }
486
+ ```
487
+
488
+ ```js
489
+ const koffi = require('koffi');
490
+ const lib = koffi.load('./length.so');
491
+
492
+ const ComputeTotalLength = lib.func('int64_t ComputeTotalLength(const char **strings)');
493
+
494
+ let strings = ['Get', 'Total', 'Length', null];
495
+ let total = ComputeTotalLength(strings);
496
+
497
+ console.log(total); // Prints 14
498
+ ```
499
+
500
+ By default, just like for objects, array arguments are copied from JS to C but not vice-versa. You can however change the direction as documented in the section on [output parameters](functions.md#output-parameters).
501
+
502
+ ## Disposable types
503
+
504
+ Disposable types allow you to register a function that will automatically called after each C to JS conversion performed by Koffi. This can be used to avoid leaking heap-allocated strings, for example.
505
+
506
+ Read the documentation for [disposable types](functions.md#heap-allocated-values) on the page about function calls.
507
+
508
+ ## Utility functions
509
+
510
+ ### Type introspection
511
+
512
+ *New in Koffi 2.0: `koffi.resolve()`*
513
+
514
+ Koffi exposes three functions to explore type information:
515
+
516
+ - `koffi.sizeof(type)` to get the size of a type
517
+ - `koffi.alignof(type)` to get the alignment of a type
518
+ - `koffi.introspect(type)` to get the definition of a type in an object containing: name, primitive, size, alignment, members (structs), reference (array, pointer) and length (array)
519
+ - `koffi.resolve(type)` to get the resolved type object from a type string
520
+
521
+ ```{note}
522
+ The value returned by `introspect()` has **changed in version 2.0**.
523
+
524
+ In Koffi 1.x, it could only be used with struct types and returned the object passed to koffi.struct() with the member names and types.
525
+
526
+ Consult the [migration guide](changes.md) for more information.
527
+ ```
528
+
529
+ Just like before, you can refer to primitive types by their name or through `koffi.types`:
530
+
531
+ ```js
532
+ // These two lines do the same:
533
+ console.log(koffi.sizeof('long'));
534
+ console.log(koffi.sizeof(koffi.types.long));
535
+ ```
536
+
537
+ ### Type aliases
538
+
539
+ *New in Koffi 2.0*
540
+
541
+ You can alias a type with `koffi.alias(name, type)`. Aliased types are completely equivalent.
@@ -0,0 +1,134 @@
1
+ /*
2
+ * _sphinx_javascript_frameworks_compat.js
3
+ * ~~~~~~~~~~
4
+ *
5
+ * Compatability shim for jQuery and underscores.js.
6
+ *
7
+ * WILL BE REMOVED IN Sphinx 6.0
8
+ * xref RemovedInSphinx60Warning
9
+ *
10
+ */
11
+
12
+ /**
13
+ * select a different prefix for underscore
14
+ */
15
+ $u = _.noConflict();
16
+
17
+
18
+ /**
19
+ * small helper function to urldecode strings
20
+ *
21
+ * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#Decoding_query_parameters_from_a_URL
22
+ */
23
+ jQuery.urldecode = function(x) {
24
+ if (!x) {
25
+ return x
26
+ }
27
+ return decodeURIComponent(x.replace(/\+/g, ' '));
28
+ };
29
+
30
+ /**
31
+ * small helper function to urlencode strings
32
+ */
33
+ jQuery.urlencode = encodeURIComponent;
34
+
35
+ /**
36
+ * This function returns the parsed url parameters of the
37
+ * current request. Multiple values per key are supported,
38
+ * it will always return arrays of strings for the value parts.
39
+ */
40
+ jQuery.getQueryParameters = function(s) {
41
+ if (typeof s === 'undefined')
42
+ s = document.location.search;
43
+ var parts = s.substr(s.indexOf('?') + 1).split('&');
44
+ var result = {};
45
+ for (var i = 0; i < parts.length; i++) {
46
+ var tmp = parts[i].split('=', 2);
47
+ var key = jQuery.urldecode(tmp[0]);
48
+ var value = jQuery.urldecode(tmp[1]);
49
+ if (key in result)
50
+ result[key].push(value);
51
+ else
52
+ result[key] = [value];
53
+ }
54
+ return result;
55
+ };
56
+
57
+ /**
58
+ * highlight a given string on a jquery object by wrapping it in
59
+ * span elements with the given class name.
60
+ */
61
+ jQuery.fn.highlightText = function(text, className) {
62
+ function highlight(node, addItems) {
63
+ if (node.nodeType === 3) {
64
+ var val = node.nodeValue;
65
+ var pos = val.toLowerCase().indexOf(text);
66
+ if (pos >= 0 &&
67
+ !jQuery(node.parentNode).hasClass(className) &&
68
+ !jQuery(node.parentNode).hasClass("nohighlight")) {
69
+ var span;
70
+ var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg");
71
+ if (isInSVG) {
72
+ span = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
73
+ } else {
74
+ span = document.createElement("span");
75
+ span.className = className;
76
+ }
77
+ span.appendChild(document.createTextNode(val.substr(pos, text.length)));
78
+ node.parentNode.insertBefore(span, node.parentNode.insertBefore(
79
+ document.createTextNode(val.substr(pos + text.length)),
80
+ node.nextSibling));
81
+ node.nodeValue = val.substr(0, pos);
82
+ if (isInSVG) {
83
+ var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
84
+ var bbox = node.parentElement.getBBox();
85
+ rect.x.baseVal.value = bbox.x;
86
+ rect.y.baseVal.value = bbox.y;
87
+ rect.width.baseVal.value = bbox.width;
88
+ rect.height.baseVal.value = bbox.height;
89
+ rect.setAttribute('class', className);
90
+ addItems.push({
91
+ "parent": node.parentNode,
92
+ "target": rect});
93
+ }
94
+ }
95
+ }
96
+ else if (!jQuery(node).is("button, select, textarea")) {
97
+ jQuery.each(node.childNodes, function() {
98
+ highlight(this, addItems);
99
+ });
100
+ }
101
+ }
102
+ var addItems = [];
103
+ var result = this.each(function() {
104
+ highlight(this, addItems);
105
+ });
106
+ for (var i = 0; i < addItems.length; ++i) {
107
+ jQuery(addItems[i].parent).before(addItems[i].target);
108
+ }
109
+ return result;
110
+ };
111
+
112
+ /*
113
+ * backward compatibility for jQuery.browser
114
+ * This will be supported until firefox bug is fixed.
115
+ */
116
+ if (!jQuery.browser) {
117
+ jQuery.uaMatch = function(ua) {
118
+ ua = ua.toLowerCase();
119
+
120
+ var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
121
+ /(webkit)[ \/]([\w.]+)/.exec(ua) ||
122
+ /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
123
+ /(msie) ([\w.]+)/.exec(ua) ||
124
+ ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
125
+ [];
126
+
127
+ return {
128
+ browser: match[ 1 ] || "",
129
+ version: match[ 2 ] || "0"
130
+ };
131
+ };
132
+ jQuery.browser = {};
133
+ jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
134
+ }