简体   繁体   中英

How to pass a 2D Javascript array into a wasm function?

I have seen many tutorials on how to pass a 1D typed Javascript array into a wasm function; however, I have not really seen a way to pass a 2D array into a wasm function. Is there a way to do this in Javascript?

Generally in such cases, you pass a 1D array but treat it as a 2D array by also passing the second dimension size and then calculating the 1D index.

By example, say each first dimension has 10 elements (zero indexed, 0 - 9) in the second dimension. To find 2D array element row 3 col 5 in the 1D array is simply a matter of calculating...

  • 3 * 10 + 5 which equals 35

So, using the 1D array, you will simply access element 35. The general formula is...

  • row * ( number_of_columns ) + col

And if given the 1D index you need to determine the 2D indices, it's a matter of...

  • row = floor( index / number_of_columns )
  • col = index % number_of_columns

Again, by example, if 35 is the 1D index, the 2D index will be...

  • row = floor( 35 / 10 ) which is 3
  • col = 35 % 10 which is 5

Similar logic can be applied for arrays of higher dimension...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM