C到WebAssembly的索引指针失败

问题描述 投票:0回答:1

我正在尝试使用C进行WebAssembly。但我无法理解以下内容:

int atAddressN(unsigned int idx) {
  unsigned int* intptr = 0;
  return intptr[idx];
}

int atAddress2(unsigned int idx) {
  unsigned int* intptr = 0;
  return intptr[2];
}

导致以下wasm / wat:

(module
 (table 0 anyfunc)
 (memory $0 1)
 (export "memory" (memory $0))
 (export "atAddressN" (func $atAddressN))
 (export "atAddress2" (func $atAddress2))
 (func $atAddressN (; 0 ;) (param $0 i32) (result i32)
  (unreachable)
  (unreachable)
 )
 (func $atAddress2 (; 1 ;) (param $0 i32) (result i32)
  (i32.load offset=8
   (i32.const 0)
  )
 )
)

所以第二个函数很好,但是第一个函数只得到(unreachable)。我应该做些其他的事情来使其编译正常吗?

c webassembly
1个回答
0
投票

空指针取消引用确实确实是一个问题,更改为:

int atAddressN(unsigned int* intptr, unsigned int idx) {
  return intptr[idx];
}

int atAddress2(unsigned int* intptr, unsigned int idx) {
  return intptr[2];
}

结果

(module
 (table 0 anyfunc)
 (memory $0 1)
 (export "memory" (memory $0))
 (export "atAddressN" (func $atAddressN))
 (export "atAddress2" (func $atAddress2))
 (func $atAddressN (; 0 ;) (param $0 i32) (param $1 i32) (result i32)
  (i32.load
   (i32.add
    (get_local $0)
    (i32.shl
     (get_local $1)
     (i32.const 2)
    )
   )
  )
 )
 (func $atAddress2 (; 1 ;) (param $0 i32) (param $1 i32) (result i32)
  (i32.load offset=8
   (get_local $0)
  )
 )
)

然后我将以0作为第一个参数调用该函数。

© www.soinside.com 2019 - 2024. All rights reserved.