@@ -155,8 +155,12 @@ function postInstantiate(baseModule, instance) {
155
155
156
156
baseModule . freeArray = freeArray ;
157
157
158
- /** Creates a new function in the module's table and returns its pointer. */
158
+ /**
159
+ * Creates a new function in the module's table and returns its pointer. Note that only actual
160
+ * WebAssembly functions, i.e. as exported by the module, are supported.
161
+ */
159
162
function newFunction ( fn ) {
163
+ if ( typeof fn . original === "function" ) fn = fn . original ;
160
164
var index = table . length ;
161
165
table . grow ( 1 ) ;
162
166
table . set ( index , fn ) ;
@@ -167,11 +171,7 @@ function postInstantiate(baseModule, instance) {
167
171
168
172
/** Gets a function by its pointer. */
169
173
function getFunction ( ptr ) {
170
- var fn = table . get ( ptr ) ;
171
- return ( ...args ) => {
172
- setargc ( args . length ) ;
173
- return fn ( ...args ) ;
174
- } ;
174
+ return wrapFunction ( table . get ( ptr ) , setargc ) ;
175
175
}
176
176
177
177
baseModule . getFunction = getFunction ;
@@ -191,6 +191,18 @@ function postInstantiate(baseModule, instance) {
191
191
} ) ) ;
192
192
}
193
193
194
+ /** Wraps a WebAssembly function while also taking care of variable arguments. */
195
+ function wrapFunction ( fn , setargc ) {
196
+ var wrap = ( ...args ) => {
197
+ setargc ( args . length ) ;
198
+ return fn ( ...args ) ;
199
+ }
200
+ // adding a function to the table with `newFunction` is limited to actual WebAssembly functions,
201
+ // hence we can't use the wrapper and instead need to provide a reference to the original
202
+ wrap . original = fn ;
203
+ return wrap ;
204
+ }
205
+
194
206
/** Instantiates an AssemblyScript module using the specified imports. */
195
207
function instantiate ( module , imports ) {
196
208
return postInstantiate (
@@ -266,7 +278,7 @@ function demangle(exports, baseModule) {
266
278
} ) ;
267
279
}
268
280
} else {
269
- curr [ name ] = wrapFunction ( elem ) ;
281
+ curr [ name ] = wrapFunction ( elem , setargc ) ;
270
282
}
271
283
} else {
272
284
if ( / ^ ( g e t | s e t ) : / . test ( name ) ) {
@@ -278,24 +290,13 @@ function demangle(exports, baseModule) {
278
290
} ) ;
279
291
}
280
292
} else if ( typeof elem === "function" ) {
281
- curr [ name ] = wrapFunction ( elem ) ;
293
+ curr [ name ] = wrapFunction ( elem , setargc ) ;
282
294
} else {
283
295
curr [ name ] = elem ;
284
296
}
285
297
}
286
298
}
287
299
288
- function wrapFunction ( fn ) {
289
- var ret = function ( ...args ) {
290
- setargc ( args . length ) ;
291
- return fn ( ...args ) ;
292
- } ;
293
- // adding a function to the table with `newFunction` is limited to actual exported WebAssembly
294
- // functions, hence we can't use the wrapper for that and instead need to pass a workaround:
295
- ret . constructor = fn ;
296
- return ret ;
297
- }
298
-
299
300
return module ;
300
301
}
301
302
0 commit comments