使用emscripten将数组传递给C函数 [英] Pass array to C function with emscripten

查看:224
本文介绍了使用emscripten将数组传递给C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这个问题类似于这个,我用了大部分答案来解决我的问题,但是我仍然遇到问题:

I think this question is similar to this one and I used most of it's answer for my problem, but I still have issues:

首先是C代码:

#include <stdio.h>

extern "C"
{
    void fillArray(int* a, int len)
    {
        for (int i = 0; i<len; i++)
        {
            a[i] = i*i;
        }

        for (int j = 0; j < len; ++j)
        {
            printf("a[%d] = %d\n", j, a[j]);
        }
    }
}

我正在传递指针到我的C函数的数组中,并填充一些信息。我用

I'm passing a pointer to an array to my C function and fill it with some information. I compile this code with

emcc -o writebmp.js dummyCode\cwrapCall.cxx -s EXPORTED_FUNCTIONS="['_fillArray']"

我的html / js代码如下:

My html/js code is the following:

<!doctype html>
<html>
  <script src="writebmp.js"></script>
  <script>
    fillArray = Module.cwrap('fillArray', null, ['number', 'number']);
    var nByte = 4
    var length = 20;
    var buffer = Module._malloc(length*nByte);
    fillArray(buffer, length);
    for (var i = 0; i < length; i++)
    {
        console.log(Module.getValue(buffer+i*nByte));
    }
  </script>
</html>

当我运行脚本时,我得到的输出是正确的,直到第12个元素,之后才是垃圾。我的内存分配太小了吗?

When I run the script the output I get is correct until the 12th element, after that it is garbage. Is the buffer I malloc too small?

推荐答案

Module.getValue 需要可选的第二个参数,表示指针应被取消引用的类型,默认情况下为'i8',这意味着32位带符号整数被取消引用为8位整数,因此您不会浪费垃圾,但会包裹错误。

Module.getValue takes an optional second argument, denoting the type that the 'pointer' should be dereferenced as and by default this is 'i8', meaning the 32 bit signed integers are being dereferenced as 8 bit integers and so you're not getting garbage, but wrap around errors.

修复此问题很简单,您只需指定将指针传递给 Module.getValue 应该被取消引用为32位有符号整数:

Fixing this is simple, you just need to specify that the 'pointer' passed to Module.getValue should be dereferenced as a 32 bit signed integer:

console.log(Module.getValue(buffer+i*nByte, 'i32'));

更改 fillArray

#include <stdint.h>

void fillArray(int32_t* a, int32_t len)

相关部分可以在此处

这篇关于使用emscripten将数组传递给C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆