@cmmd-center/forge 0.13.6 → 0.13.7

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 (78) hide show
  1. package/dist/{BunHttpServer-DKvSpNd1.cjs → BunHttpServer-C7-1JJ7b.cjs} +4 -4
  2. package/dist/{BunHttpServer-CDh4Vioe.mjs → BunHttpServer-CVPGkizx.mjs} +4 -4
  3. package/dist/{BunServices-D6PAheqS.mjs → BunServices-CPrZSIfE.mjs} +2 -2
  4. package/dist/{BunServices-DDh7Whyx.cjs → BunServices-Dl-3897e.cjs} +2 -2
  5. package/dist/{Cache-BVilO50s.mjs → Cache-C9cwdCDt.mjs} +2 -2
  6. package/dist/{Cache-DCF22Dfk.cjs → Cache-Cf3ARNaS.cjs} +2 -2
  7. package/dist/{HttpServer-ClsGgAq1.mjs → HttpServer-COaBeM7-.mjs} +2 -2
  8. package/dist/{HttpServer-D1gSU7NX.cjs → HttpServer-CggZzScj.cjs} +3 -3
  9. package/dist/{NodeHttpServer-Dfc7nSMq.cjs → NodeHttpServer-Bi339XFk.cjs} +5 -5
  10. package/dist/{NodeHttpServer-DT0TF8s4.mjs → NodeHttpServer-UQnvZnmu.mjs} +5 -5
  11. package/dist/{NodePTY-loxi8Vku.mjs → NodePTY-B1u6RHXk.mjs} +2 -2
  12. package/dist/{NodePTY-S4tPEwZc.cjs → NodePTY-UOaRyQsj.cjs} +2 -2
  13. package/dist/{NodeServices-Cb0rXFb2.cjs → NodeServices-CKFIZVu5.cjs} +2 -2
  14. package/dist/{NodeServices-DE8jhdcU.cjs → NodeServices-R0BZsZ72.cjs} +1 -1
  15. package/dist/{NodeServices-BahzLhbo.mjs → NodeServices-z1Ac4lEO.mjs} +2 -2
  16. package/dist/{NodeSqliteClient-DqFjB3u_.mjs → NodeSqliteClient-BrzqdOsF.mjs} +4 -4
  17. package/dist/{NodeSqliteClient-qjBWAOGq.cjs → NodeSqliteClient-CyJvo9y9.cjs} +4 -4
  18. package/dist/{NodeTerminal-rYbifme7.cjs → NodeTerminal-B89MobLp.cjs} +2 -2
  19. package/dist/{NodeTerminal-BPw7bktz.mjs → NodeTerminal-pYVVRTiD.mjs} +2 -2
  20. package/dist/{Path-CGCc_dDx.cjs → Path-BunGrE8F.cjs} +72 -1
  21. package/dist/{Path-C851t6sC.mjs → Path-evOm-H0Q.mjs} +61 -2
  22. package/dist/{SqlError-CzB6p9lL.cjs → SqlError-1wIMjXAf.cjs} +2 -2
  23. package/dist/{SqlError-3aqibZrj.mjs → SqlError-CezTFGvr.mjs} +2 -2
  24. package/dist/{SqliteClient-DTWCGkrj.mjs → SqliteClient-D3Yd3ZHn.mjs} +3 -3
  25. package/dist/{SqliteClient-Cq1peWN1.cjs → SqliteClient-bo7iui1t.cjs} +3 -3
  26. package/dist/bin.cjs +4818 -3951
  27. package/dist/bin.mjs +4356 -3495
  28. package/dist/client/assets/{CanvasPanel-BwSV27Ct.js → CanvasPanel-C21OO2qi.js} +2 -2
  29. package/dist/client/assets/{CompositeItem-CZk3X-ud.js → CompositeItem-naFGUtSL.js} +2 -2
  30. package/dist/client/assets/{DiffPanel-ixzJ8GwW.js → DiffPanel-D_YC838v.js} +3 -3
  31. package/dist/client/assets/{DiffPanel.logic-D-SDgBF9.js → DiffPanel.logic-Bqk_6nE1.js} +2 -2
  32. package/dist/client/assets/DiffPanelShell-D1KMJc9z.js +2532 -0
  33. package/dist/client/assets/{DiffWorkerPoolProvider-BO_xUE3R.js → DiffWorkerPoolProvider-B5tF5UEc.js} +10 -10
  34. package/dist/client/assets/PullRequestCodePanel-ClD3ZXbi.js +5 -0
  35. package/dist/client/assets/Virtualizer-cvcMb_IQ.js +2 -0
  36. package/dist/client/assets/{canvasStateStore-5DH2Z-PG.js → canvasStateStore-CpNOSHBt.js} +2 -2
  37. package/dist/client/assets/cmmdAuthRedirect-DdH7K490.js +2 -0
  38. package/dist/client/assets/index-BE83u7Db.css +1 -0
  39. package/dist/client/assets/index-yLc4LtMp.js +153 -0
  40. package/dist/client/assets/{popover-Dxp_1Sz0.js → popover-BajtiGgk.js} +2 -2
  41. package/dist/client/assets/src-D6fBWY6U.js +3 -0
  42. package/dist/client/assets/{toggle-B-GE6jq_.js → toggle-BRNCUuRT.js} +2 -2
  43. package/dist/client/index.html +11 -11
  44. package/dist/forge-build.json +1 -1
  45. package/dist/node_modules/@ff-labs/fff-bin-linux-x64-gnu/libfff_c.so +0 -0
  46. package/dist/node_modules/@ff-labs/fff-bin-linux-x64-gnu/package.json +27 -0
  47. package/dist/node_modules/@ff-labs/fff-node/.bun-tag-689ffe3747e13d19 +0 -0
  48. package/dist/node_modules/@ff-labs/fff-node/README.md +126 -0
  49. package/dist/node_modules/@ff-labs/fff-node/dist/src/binary.d.ts +22 -0
  50. package/dist/node_modules/@ff-labs/fff-node/dist/src/binary.js +144 -0
  51. package/dist/node_modules/@ff-labs/fff-node/dist/src/fff-api.d.ts +581 -0
  52. package/dist/node_modules/@ff-labs/fff-node/dist/src/fff-api.js +24 -0
  53. package/dist/node_modules/@ff-labs/fff-node/dist/src/ffi.d.ts +137 -0
  54. package/dist/node_modules/@ff-labs/fff-node/dist/src/ffi.js +1191 -0
  55. package/dist/node_modules/@ff-labs/fff-node/dist/src/finder.d.ts +353 -0
  56. package/dist/node_modules/@ff-labs/fff-node/dist/src/finder.js +488 -0
  57. package/dist/node_modules/@ff-labs/fff-node/dist/src/index.d.ts +47 -0
  58. package/dist/node_modules/@ff-labs/fff-node/dist/src/index.js +47 -0
  59. package/dist/node_modules/@ff-labs/fff-node/dist/src/platform.d.ts +27 -0
  60. package/dist/node_modules/@ff-labs/fff-node/dist/src/platform.js +120 -0
  61. package/dist/node_modules/@ff-labs/fff-node/package.json +76 -0
  62. package/dist/node_modules/@yuuang/ffi-rs-linux-x64-gnu/README.md +794 -0
  63. package/dist/node_modules/@yuuang/ffi-rs-linux-x64-gnu/ffi-rs.linux-x64-gnu.node +0 -0
  64. package/dist/node_modules/@yuuang/ffi-rs-linux-x64-gnu/package.json +21 -0
  65. package/dist/node_modules/ffi-rs/LICENSE +21 -0
  66. package/dist/node_modules/ffi-rs/README.md +794 -0
  67. package/dist/node_modules/ffi-rs/index.d.ts +222 -0
  68. package/dist/node_modules/ffi-rs/index.js +380 -0
  69. package/dist/node_modules/ffi-rs/package.json +76 -0
  70. package/dist/{open-FIgTDosf.mjs → open-D8mGyWmt.mjs} +3 -3
  71. package/package.json +2 -1
  72. package/dist/client/assets/DiffPanelShell-Dz5Wvcvi.js +0 -2532
  73. package/dist/client/assets/PullRequestCodePanel-CW4RK1Oa.js +0 -5
  74. package/dist/client/assets/cmmdAuthRedirect-D68LO-sw.js +0 -2
  75. package/dist/client/assets/diffTargetResolution-WqxwJEax.js +0 -2
  76. package/dist/client/assets/index-DivaIsZ4.css +0 -1
  77. package/dist/client/assets/index-UXWCtM6c.js +0 -153
  78. package/dist/client/assets/src-n5cTLVWV.js +0 -3
@@ -0,0 +1,794 @@
1
+ # ffi-rs
2
+
3
+ <div>
4
+ <a href="./README.md">English</a> | <a href="./README_Zh.md">简体中文</a>
5
+ </div>
6
+
7
+ A module written in Rust and N-API provides interface (FFI) features for Node.js
8
+
9
+ <div align="">
10
+ <a href="https://github.com/zhangyuang/node-ffi-rs/actions" target="_blank"><img src="https://github.com/zhangyuang/node-ffi-rs/workflows/CI/badge.svg" alt="githubActions" /></a>
11
+ <a href="https://www.npmjs.com/package/ffi-rs" target="_blank"><img src="https://img.shields.io/npm/dm/ffi-rs">
12
+ </a>
13
+ <a href="https://www.npmjs.com/package/ffi-rs" target="_blank"><img src="https://img.shields.io/npm/unpacked-size/@yuuang/ffi-rs-linux-x64-gnu">
14
+ </a>
15
+ </div>
16
+
17
+ ## Description
18
+
19
+ [ffi-rs](https://github.com/zhangyuang/node-ffi-rs) is a high-performance module with small binary size written in Rust and N-API that provides FFI (Foreign Function Interface) features for Node.js. It allows developers to call functions written in other languages such as C++, C, and Rust directly from JavaScript without writing any C++ code.
20
+
21
+ This module aims to provide similar functionality to the node-ffi module but with a completely rewritten underlying codebase. The node-ffi module has been unmaintained for several years and is no longer usable, so ffi-rs was developed to fill that void.
22
+
23
+ ## Features
24
+
25
+ * High performance ✨
26
+ * Small binary size
27
+ * Better type hints 🧐
28
+ * Simpler data description and API interface 💗
29
+ * Support more different data types between `Node.js` and `C` 😊
30
+ * Support modifying data in place 🥸
31
+ * Provide many ways to handle pointer type directly 🐮
32
+ * Support running ffi task [in a new thread](#runInNewThread) 🤩️
33
+ * Support output [errno](#errno) info 🤔️
34
+ * No need to use [ref](https://www.npmjs.com/package/ref) to handle pointer 🤫
35
+
36
+ ## Benchmark
37
+
38
+ ```bash
39
+ $ node bench/bench.js
40
+ Running "ffi" suite...
41
+ Progress: 100%
42
+
43
+ ffi-napi:
44
+ 2 028 ops/s, ±4.87% | slowest, 99.24% slower
45
+
46
+ ffi-rs:
47
+ 318 467 ops/s, ±0.17% | fastest
48
+
49
+ Finished 2 cases!
50
+ Fastest: ffi-rs
51
+ Slowest: ffi-napi
52
+ ```
53
+
54
+ ### How to sponsor me
55
+
56
+ There are two ways to sponsor me both Alipay and WeChat
57
+
58
+ Eth address: 0x87a2575a5d4dbD5f965e3e3a3d20641BC9a5d192
59
+
60
+ <div style="display:flex">
61
+ <img src="https://doc.ssr-fc.com/images/wepay.jpg" width=200>
62
+ <img src="https://doc.ssr-fc.com/images/alipay.jpg" width=200>
63
+ </div>
64
+
65
+ ## Changelog
66
+
67
+ See [CHANGELOG.md](./CHANGELOG.md)
68
+
69
+ ## Ecosystem
70
+
71
+ [abstract-socket-rs](https://github.com/zhangyuang/abstract-socket-rs)
72
+
73
+ ## Install
74
+
75
+ ```bash
76
+ $ npm i ffi-rs
77
+ ```
78
+
79
+ ## Supported Types
80
+
81
+ Currently, ffi-rs only supports these types of parameters and return values. However, support for more types may be added in the future based on actual usage scenarios.
82
+
83
+ ### Basic Types
84
+
85
+ * [string](#basic-types)
86
+ * [wideString|wstring](#basic-types)
87
+ * [u8](#basic-types)
88
+ * [i16](#basic-types)
89
+ * [i32](#basic-types)
90
+ * [i64](#basic-types)
91
+ * [bigInt](#basic-types)
92
+ * [u64](#basic-types)
93
+ * [u32](#basic-types)
94
+ * [void](#basic-types) (like js undefined)
95
+ * [float](#basic-types) (can only be used as paramsType instead of retType)
96
+ * [double](#basic-types)
97
+ * [boolean](#basic-types)
98
+
99
+ ### Reference Types
100
+
101
+ * [pointer](#pointer)
102
+ * [u8Array](#buffer) (buffer)
103
+ * [i16Array](#array)
104
+ * [i32Array](#array)
105
+ * [stringArray](#array)
106
+ * [doubleArray](#array)
107
+ * [floatArray](#array) (can only be used as paramsType instead of retType)
108
+ * [structArray](#array)
109
+ * [object](#struct) (Nested object is also supported in the latest version)
110
+ * [function](#function)
111
+
112
+ ### C++ Class
113
+
114
+ If you want to call a C++ function whose argument type is a class, you can use the `pointer` type. See [tutorial](#C++)
115
+
116
+ ## Supported Platforms
117
+
118
+ Note: You need to make sure that the compilation environment of the dynamic library is the same as the installation and runtime environment of the `ffi-rs` call.
119
+
120
+ * darwin-x64
121
+ * darwin-arm64
122
+ * linux-x64-gnu
123
+ * linux-x64-musl
124
+ * win32-x64-msvc
125
+ * win32-ia32-msvc
126
+ * win32-arm64-msvc
127
+ * linux-arm64-gnu
128
+ * linux-arm64-musl
129
+ * linux-arm-gnueabihf
130
+ * android-arm64
131
+
132
+ ## Usage
133
+
134
+ View [tests/index.ts](./tests/index.ts) for the latest usage
135
+
136
+ Here is an example of how to use ffi-rs:
137
+
138
+ For the following C++ code, we compile this file into a dynamic library
139
+
140
+ ### Write Foreign Function Code
141
+
142
+ Note: The return value type of a function must be of type C
143
+
144
+ ```cpp
145
+ #include <cstdio>
146
+ #include <cstring>
147
+ #include <iostream>
148
+ #include <string>
149
+
150
+ extern "C" int sum(int a, int b) { return a + b; }
151
+
152
+ extern "C" double doubleSum(double a, double b) { return a + b; }
153
+
154
+ extern "C" const char *concatenateStrings(const char *str1, const char *str2) {
155
+ std::string result = std::string(str1) + std::string(str2);
156
+ char *cstr = new char[result.length() + 1];
157
+ strcpy(cstr, result.c_str());
158
+ return cstr;
159
+ }
160
+
161
+ extern "C" void noRet() { printf("%s", "hello world"); }
162
+ extern "C" bool return_opposite(bool input) { return !input; }
163
+ extern "C" uint32_t testU32(uint32_t a, uint32_t b) { return a + b; }
164
+ ```
165
+
166
+ ### Compile C Code into a Dynamic Library
167
+
168
+ ```bash
169
+ $ g++ -dynamiclib -o libsum.so cpp/sum.cpp # macOS
170
+ $ g++ -shared -o libsum.so cpp/sum.cpp # Linux
171
+ $ g++ -shared -o sum.dll cpp/sum.cpp # Windows
172
+ ```
173
+
174
+ ### Call Dynamic Library Using ffi-rs
175
+
176
+ Then you can use `ffi-rs` to invoke the dynamic library file that contains functions.
177
+
178
+ ### Initialization
179
+
180
+ It's suggested to develop with TypeScript to get type hints
181
+
182
+ ```js
183
+ const {
184
+ equal
185
+ } = require('assert')
186
+ const {
187
+ load,
188
+ DataType,
189
+ open,
190
+ close,
191
+ arrayConstructor,
192
+ define
193
+ } = require('ffi-rs')
194
+ const a = 1
195
+ const b = 100
196
+ const dynamicLib = platform === 'win32' ? './sum.dll' : "./libsum.so"
197
+ // First open dynamic library with key for close
198
+ // It only needs to be opened once.
199
+ open({
200
+ library: 'libsum', // key
201
+ path: dynamicLib // path
202
+ })
203
+ const r = load({
204
+ library: "libsum", // path to the dynamic library file
205
+ funcName: 'sum', // the name of the function to call
206
+ retType: DataType.I32, // the return value type
207
+ paramsType: [DataType.I32, DataType.I32], // the parameter types
208
+ paramsValue: [a, b] // the actual parameter values
209
+ // freeResultMemory: true, // whether or not need to free the result of return value memory automatically, default is false
210
+ })
211
+ equal(r, a + b)
212
+ // Release library memory when you're not using it.
213
+ close('libsum')
214
+
215
+ // Use define function to define a function signature
216
+ const res = define({
217
+ sum: {
218
+ library: "libsum",
219
+ retType: DataType.I32,
220
+ paramsType: [DataType.I32, DataType.I32],
221
+ },
222
+ atoi: {
223
+ library: "libnative",
224
+ retType: DataType.I32,
225
+ paramsType: [DataType.String],
226
+ }
227
+ })
228
+ equal(res.sum([1, 2]), 3)
229
+ equal(res.atoi(["1000"]), 1000)
230
+ ```
231
+
232
+ ### Load Main Program Handle
233
+
234
+ You can also pass an empty path string in the `open` function like [ffi-napi](https://github.com/node-ffi-napi/node-ffi-napi?tab=readme-ov-file#example) to get the main program handle. Refer to [dlopen](https://man7.org/linux/man-pages/man3/dlopen.3.html)
235
+
236
+ ```js
237
+ open({
238
+ library: "libnative",
239
+ path: "",
240
+ });
241
+ // In Darwin/Linux, you can call the atoi function which is included in the basic C library
242
+ equal(
243
+ load({
244
+ library: "libnative",
245
+ funcName: "atoi",
246
+ retType: DataType.I32,
247
+ paramsType: [DataType.String],
248
+ paramsValue: ["1000"],
249
+ }),
250
+ 1000,
251
+ );
252
+ ```
253
+
254
+ ### Basic Types
255
+
256
+ `number|string|boolean|double|void` are basic types
257
+
258
+ ```js
259
+ const c = "foo"
260
+ const d = c.repeat(200)
261
+
262
+ equal(c + d, load({
263
+ library: 'libsum',
264
+ funcName: 'concatenateStrings',
265
+ retType: DataType.String,
266
+ paramsType: [DataType.String, DataType.String],
267
+ paramsValue: [c, d]
268
+ }))
269
+
270
+ equal(undefined, load({
271
+ library: 'libsum',
272
+ funcName: 'noRet',
273
+ retType: DataType.Void,
274
+ paramsType: [],
275
+ paramsValue: []
276
+ }))
277
+
278
+ equal(1.1 + 2.2, load({
279
+ library: 'libsum',
280
+ funcName: 'doubleSum',
281
+ retType: DataType.Double,
282
+ paramsType: [DataType.Double, DataType.Double],
283
+ paramsValue: [1.1, 2.2]
284
+ }))
285
+ const bool_val = true
286
+ equal(!bool_val, load({
287
+ library: 'libsum',
288
+ funcName: 'return_opposite',
289
+ retType: DataType.Boolean,
290
+ paramsType: [DataType.Boolean],
291
+ paramsValue: [bool_val],
292
+ }))
293
+
294
+ // U32 type usage
295
+ equal(3147483647, load({
296
+ library: 'libsum',
297
+ funcName: 'testU32',
298
+ retType: DataType.U32,
299
+ paramsType: [DataType.U32, DataType.U32],
300
+ paramsValue: [2147483647, 1000000000],
301
+ }))
302
+ ```
303
+
304
+ ### Buffer
305
+
306
+ In the latest version, `ffi-rs` supports modifying data in place.
307
+
308
+ The sample code is as follows
309
+
310
+ ```c
311
+ extern int modifyData(char* buffer) {
312
+ // modify buffer data in place
313
+ }
314
+ ```
315
+
316
+ ```js
317
+ const arr = Buffer.alloc(200) // create buffer
318
+ const res = load({
319
+ library: "libsum",
320
+ funcName: "modifyData",
321
+ retType: DataType.I32,
322
+ paramsType: [
323
+ DataType.U8Array
324
+ ],
325
+ paramsValue: [arr]
326
+ })
327
+ console.log(arr) // buffer data can be updated
328
+ ```
329
+
330
+ ### Array
331
+
332
+ When using `array` as `retType` , you should use `arrayConstructor` to specify the array type with a legal length which is important.
333
+
334
+ If the length is incorrect, the program may exit abnormally
335
+
336
+ ```cpp
337
+ extern "C" int *createArrayi32(const int *arr, int size) {
338
+ int *vec = (int *)malloc((size) * sizeof(int));
339
+
340
+ for (int i = 0; i < size; i++) {
341
+ vec[i] = arr[i];
342
+ }
343
+ return vec;
344
+ }
345
+ extern "C" double *createArrayDouble(const double *arr, int size) {
346
+ double *vec = (double *)malloc((size) * sizeof(double));
347
+ for (int i = 0; i < size; i++) {
348
+ vec[i] = arr[i];
349
+ }
350
+ return vec;
351
+ }
352
+
353
+ extern "C" char **createArrayString(char **arr, int size) {
354
+ char **vec = (char **)malloc((size) * sizeof(char *));
355
+ for (int i = 0; i < size; i++) {
356
+ vec[i] = arr[i];
357
+ }
358
+ return vec;
359
+ }
360
+ ```
361
+
362
+ ```js
363
+ let bigArr = new Array(100).fill(100)
364
+ deepStrictEqual(bigArr, load({
365
+ library: 'libsum',
366
+ funcName: 'createArrayi32',
367
+ retType: arrayConstructor({
368
+ type: DataType.I32Array,
369
+ length: bigArr.length
370
+ }),
371
+ paramsType: [DataType.I32Array, DataType.I32],
372
+ paramsValue: [bigArr, bigArr.length],
373
+ }))
374
+
375
+ let bigDoubleArr = new Array(5).fill(1.1)
376
+ deepStrictEqual(bigDoubleArr, load({
377
+ library: 'libsum',
378
+ funcName: 'createArrayDouble',
379
+ retType: arrayConstructor({
380
+ type: DataType.DoubleArray,
381
+ length: bigDoubleArr.length
382
+ }),
383
+ paramsType: [DataType.DoubleArray, DataType.I32],
384
+ paramsValue: [bigDoubleArr, bigDoubleArr.length],
385
+ }))
386
+ let stringArr = [c, c.repeat(20)]
387
+
388
+ deepStrictEqual(stringArr, load({
389
+ library: 'libsum',
390
+ funcName: 'createArrayString',
391
+ retType: arrayConstructor({
392
+ type: DataType.StringArray,
393
+ length: stringArr.length
394
+ }),
395
+ paramsType: [DataType.StringArray, DataType.I32],
396
+ paramsValue: [stringArr, stringArr.length],
397
+ }))
398
+ ```
399
+
400
+ ### Pointer
401
+
402
+ These functions are used to handle pointer types in `ffi-rs` . We use `DataType.External` to pass pointers between `Node.js` and `C` .
403
+
404
+ #### Create Pointer
405
+
406
+ Use `createPointer` to create a pointer for specific type in the code as follows:
407
+
408
+ ```js
409
+ extern "C"
410
+ void receiveNumPointer(const int * num)
411
+
412
+ // use the rust type expression the pointer type is *const i32
413
+ const pointer: JsExternal[] = createPointer({
414
+ paramsType: [DataType.I32],
415
+ paramsValue: [100],
416
+ })
417
+
418
+ load({
419
+ library: "libsum",
420
+ funcName: "receiveNumPointer",
421
+ paramsType: [DataType.External],
422
+ paramsValue: pointer,
423
+ retType: DataType.Void,
424
+ })
425
+ ```
426
+
427
+ #### unwrapPointer
428
+
429
+ Use `createPointer` to create a data type which store in heap will receive a double pointer means a pointer to a pointer.
430
+ So we need to use `unwrapPointer` to get the inner pointer when call foreign function.
431
+
432
+ ```js
433
+ extern "C"
434
+ void receiveStringPointer(const char * str)
435
+
436
+ // because of string is a pointer, so the pointer is a double pointer means a pointer to a string pointer
437
+ // use the rust type expression pointer type is *mut *const char
438
+ const pointer: JsExternal[] = createPointer({
439
+ paramsType: [DataType.String],
440
+ paramsValue: ["hello"],
441
+ })
442
+
443
+ load({
444
+ library: "libsum",
445
+ funcName: "receiveStringPointer",
446
+ paramsType: [DataType.External],
447
+ paramsValue: unwrapPointer(pointer), // use the unwrapPointer to get the inner *mut *const char pointer, which points to a *const char value
448
+ retType: DataType.Void,
449
+ })
450
+ ```
451
+
452
+ #### restorePointer
453
+
454
+ If you want to restore the pointer to the original value, you can use the `restorePointer` function. Corresponds to `createPointer` ,
455
+ it can receive the result of `createPointer` and return the original pointer directly without `wrapPointer` or `unwrapPointer` .
456
+
457
+ ```js
458
+ const pointer: JsExternal[] = createPointer({
459
+ paramsType: [DataType.String],
460
+ paramsValue: ["hello"],
461
+ })
462
+ const str = restorePointer({
463
+ retType: [DataType.String],
464
+ paramsValue: pointer,
465
+ })
466
+ equal(str, "hello")
467
+ ```
468
+
469
+ #### wrapPointer
470
+
471
+ Use `wrapPointer` when you want to restore the foreign function return value.
472
+
473
+ ```js
474
+ extern "C" const char * returnStringPointer() {
475
+ char * str = new char[6];
476
+ strcpy(str, "hello");
477
+ return str;
478
+ }
479
+ // the stringPointer type is *const char, we need to convert it to *mut *const char before call restorePointer
480
+ const stringPointer = load({
481
+ library: "libsum",
482
+ funcName: "returnStringPointer",
483
+ retType: DataType.External,
484
+ paramsType: [DataType.String],
485
+ paramsValue: ["hello"],
486
+ })
487
+
488
+ const wrapStringPointer = wrapPointer([stringPointer])
489
+
490
+ const str = restorePointer({
491
+ retType: [DataType.String],
492
+ paramsValue: wrapStringPointer,
493
+ })
494
+ equal(str, "hello")
495
+ ```
496
+
497
+ #### freePointer
498
+
499
+ Use `freePointer` to free the pointer when it is no longer in use.
500
+
501
+ ```js
502
+ const i32Ptr = createPointer({
503
+ paramsType: [DataType.I32],
504
+ paramsValue: [100]
505
+ })
506
+ const i32Data = restorePointer({
507
+ paramsValue: i32Ptr
508
+ retType: [DataType.I32],
509
+ })
510
+ freePointer({
511
+ paramsType: [DataType.I32],
512
+ paramsValue: i32Ptr,
513
+ pointerType: PointerType.RsPointer
514
+ })
515
+
516
+ extern "C" const char * returnStringPointer() {
517
+ char * str = new char[6];
518
+ strcpy(str, "hello");
519
+ return str;
520
+ }
521
+ const stringPointer = load({
522
+ library: "libsum",
523
+ funcName: "returnStringPointer",
524
+ retType: DataType.External,
525
+ paramsType: [DataType.String],
526
+ paramsValue: ["hello"],
527
+ })
528
+ freePointer({
529
+ paramsType: [DataType.External],
530
+ paramsValue: [stringPointer],
531
+ pointerType: PointerType.CPointer // will use libc::free to free the memory
532
+ })
533
+ ```
534
+
535
+ ### Struct
536
+
537
+ To create a C struct or get a C struct as a return type, you need to define the types of the parameters strictly in the order in which the fields of the C structure are defined.
538
+
539
+ `ffi-rs` provides a C struct named `Person` with many types of fields in [sum.cpp](./cpp/sum.cpp#L48)
540
+
541
+ The example call method about how to call a foreign function to create a `Person` struct or use `Person` struct as a return value is [here](./tests/struct.ts#L27)
542
+
543
+ #### Use array in struct
544
+
545
+ There are two types of arrays in C language like `int* array` and `int array[100]` that have some different usages.
546
+
547
+ The first type `int* array` is a pointer type storing the first address of the array.
548
+
549
+ The second type `int array[100]` is a fixed-length array and each element in the array has a continuous address.
550
+
551
+ If you use an array as a function parameter, this usually passes an array pointer regardless of which type you define. But if the array type is defined in a struct, the two types of array definitions will cause different sizes and alignments of the struct.
552
+
553
+ So, `ffi-rs` needs to distinguish between the two types.
554
+
555
+ By default, `ffi-rs` uses dynamic arrays to calculate struct. If you confirm there is a static array, you can define it in this way:
556
+
557
+ ```c
558
+ typedef struct Person {
559
+ //...
560
+ uint8_t staticBytes[16];
561
+ //...
562
+ } Person;
563
+
564
+ // use arrayConstructor and set ffiTypeTag field to DataType.StackArray
565
+ staticBytes: arrayConstructor({
566
+ type: DataType.U8Array,
567
+ length: parent.staticBytes.length,
568
+ ffiTypeTag: FFITypeTag.StackArray
569
+ }),
570
+ ```
571
+
572
+ ## Function
573
+
574
+ `ffi-rs` supports passing JS function pointers to C functions, like this:
575
+
576
+ ```cpp
577
+ typedef const void (*FunctionPointer)(int a, bool b, char *c, double d,
578
+ char **e, int *f, Person *g);
579
+
580
+ extern "C" void callFunction(FunctionPointer func) {
581
+ printf("callFunction\n");
582
+
583
+ for (int i = 0; i < 2; i++) {
584
+ int a = 100;
585
+ bool b = false;
586
+ double d = 100.11;
587
+ char *c = (char *)malloc(14 * sizeof(char));
588
+ strcpy(c, "Hello, World!");
589
+
590
+ char **stringArray = (char **)malloc(sizeof(char *) * 2);
591
+ stringArray[0] = strdup("Hello");
592
+ stringArray[1] = strdup("world");
593
+
594
+ int *i32Array = (int *)malloc(sizeof(int) * 3);
595
+ i32Array[0] = 101;
596
+ i32Array[1] = 202;
597
+ i32Array[2] = 303;
598
+
599
+ Person *p = createPerson();
600
+ func(a, b, c, d, stringArray, i32Array, p);
601
+ }
602
+ }
603
+ ```
604
+
605
+ Corresponding to the code above, you can use `ffi-rs` like this:
606
+
607
+ ```js
608
+ const testFunction = () => {
609
+ const func = (a, b, c, d, e, f, g) => {
610
+ equal(a, 100);
611
+ equal(b, false);
612
+ equal(c, "Hello, World!");
613
+ equal(d, "100.11");
614
+ deepStrictEqual(e, ["Hello", "world"]);
615
+ deepStrictEqual(f, [101, 202, 303]);
616
+ deepStrictEqual(g, person);
617
+ logGreen("test function succeed");
618
+ // free function memory when it is not in use
619
+ freePointer({
620
+ paramsType: [funcConstructor({
621
+ paramsType: [
622
+ DataType.I32,
623
+ DataType.Boolean,
624
+ DataType.String,
625
+ DataType.Double,
626
+ arrayConstructor({
627
+ type: DataType.StringArray,
628
+ length: 2
629
+ }),
630
+ arrayConstructor({
631
+ type: DataType.I32Array,
632
+ length: 3
633
+ }),
634
+ personType,
635
+ ],
636
+ retType: DataType.Void,
637
+ })],
638
+ paramsValue: funcExternal
639
+ })
640
+ if (!process.env.MEMORY) {
641
+ close("libsum");
642
+ }
643
+ };
644
+ // suggest using createPointer to create a function pointer for manual memory management
645
+ const funcExternal = createPointer({
646
+ paramsType: [funcConstructor({
647
+ paramsType: [
648
+ DataType.I32,
649
+ DataType.Boolean,
650
+ DataType.String,
651
+ DataType.Double,
652
+ arrayConstructor({
653
+ type: DataType.StringArray,
654
+ length: 2
655
+ }),
656
+ arrayConstructor({
657
+ type: DataType.I32Array,
658
+ length: 3
659
+ }),
660
+ personType,
661
+ ],
662
+ retType: DataType.Void,
663
+ })],
664
+ paramsValue: [func]
665
+ })
666
+ load({
667
+ library: "libsum",
668
+ funcName: "callFunction",
669
+ retType: DataType.Void,
670
+ paramsType: [
671
+ DataType.External,
672
+ ],
673
+ paramsValue: unwrapPointer(funcExternal),
674
+ });
675
+ }
676
+ ```
677
+
678
+ The function parameters support all types in the example above.
679
+
680
+ Attention: since the vast majority of scenarios developers pass JS functions to C as callbacks, `ffi-rs` will create [threadsafe_function](https://nodejs.org/api/n-api.html#napi_threadsafe_function) from JS functions which means the JS function will be called asynchronously, and the Node.js process will not exit automatically.
681
+
682
+ ## C++
683
+
684
+ We'll provide more examples from real-world scenarios. If you have any ideas, please submit an issue.
685
+
686
+ ### Class type
687
+
688
+ In C++ scenarios, we can use `DataType.External` to get a class type pointer.
689
+
690
+ In the code below, we use C types to wrap C++ types such as converting `char *` to `std::string` and returning a class pointer:
691
+
692
+ ```cpp
693
+ MyClass *createMyClass(std::string name, int age) {
694
+ return new MyClass(name, age);
695
+ }
696
+
697
+ extern "C" MyClass *createMyClassFromC(const char *name, int age) {
698
+ return createMyClass(std::string(name), age);
699
+ }
700
+
701
+ extern "C" void printMyClass(MyClass *instance) { instance->print(); }
702
+ ```
703
+
704
+ And then, it can be called by the following code:
705
+
706
+ ```js
707
+ const classPointer = load({
708
+ library: "libsum",
709
+ funcName: "createMyClassFromC",
710
+ retType: DataType.External,
711
+ paramsType: [
712
+ DataType.String,
713
+ DataType.I32
714
+ ],
715
+ paramsValue: ["classString", 26],
716
+ });
717
+ load({
718
+ library: "libsum",
719
+ funcName: "printMyClass",
720
+ retType: DataType.External,
721
+ paramsType: [
722
+ DataType.External,
723
+ ],
724
+ paramsValue: [classPointer],
725
+ })
726
+ freePointer({
727
+ paramsType: [DataType.External],
728
+ paramsValue: [classPointer],
729
+ pointerType: PointerType.CPointer
730
+ })
731
+ ```
732
+
733
+ ## errno
734
+
735
+ By default, `ffi-rs` will not output [errno](https://man7.org/linux/man-pages/man3/errno.3.html) info. Developers can get it by passing `errno: true` when calling the open method like:
736
+
737
+ ```js
738
+ load({
739
+ library: 'libnative',
740
+ funcName: 'setsockopt',
741
+ retType: DataType.I32,
742
+ paramsType: [DataType.I32, DataType.I32, DataType.I32, DataType.External, DataType.I32],
743
+ paramsValue: [socket._handle.fd, level, option, pointer[0], 4],
744
+ errno: true // set errno as true
745
+ })
746
+
747
+ // The above code will return an object including three fields: errnoCode, errnoMessage, and the foreign function return value
748
+ // { errnoCode: 22, errnoMessage: 'Invalid argument (os error 22)', value: -1 }
749
+ ```
750
+
751
+ ## Memory Management
752
+
753
+ It's important to free the memory allocations during a single ffi call to prevent memory leaks.
754
+
755
+ What kinds of data memory are allocated in this?
756
+
757
+ * Call parameters in the Rust environment which are allocated in the heap like `String`
758
+ * Return value which in the C environment which are allocated in the heap like `char*`
759
+
760
+ By default, `ffi-rs` will free call parameters memory which are allocated in Rust.
761
+
762
+ But it will not free the return value from the C side since some C dynamic libraries will manage their memory automatically (when ffi-rs >= 1.0.79)
763
+
764
+ There are two ways to prevent `ffi-rs` from releasing memory:
765
+
766
+ * Set `freeResultMemory: false` when calling `load` method, the default value is false
767
+
768
+ If you set freeResultMemory to false, `ffi-rs` will not release the return result memory which was allocated in the C environment
769
+
770
+ * Use `DataType.External` as paramsType or retType
771
+
772
+ If developers use `DataType.External` as paramsType or retType, please use `freePointer` to release the memory of the pointer when this memory is no longer in use. ref [tests/index.ts](./tests/index.ts#L212)
773
+
774
+ ## runInNewThread
775
+
776
+ `ffi-rs` supports running ffi tasks in a new thread without blocking the main thread, which is useful for CPU-intensive tasks.
777
+
778
+ To use this feature, you can pass the `runInNewThread` option to the load method:
779
+
780
+ ```js
781
+ const testRunInNewThread = async () => {
782
+ // will return a promise but the task will run in a new thread
783
+ load({
784
+ library: "libsum",
785
+ funcName: "sum",
786
+ retType: DataType.I32,
787
+ paramsType: [DataType.I32, DataType.I32],
788
+ paramsValue: [1, 2],
789
+ runInNewThread: true,
790
+ }).then(res => {
791
+ equal(res, 3)
792
+ })
793
+ }
794
+ ```