emscripten:我如何解决UnboundTypeError [英] emscripten: How can I solve UnboundTypeError

查看:1446
本文介绍了emscripten:我如何解决UnboundTypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用emscripten构建一个程序,它使用std :: vector和std :: map并且编译成功。
然而,当我在网络浏览器(firefox / chrome)上运行它时,UnboundTypeError被捕获。

I am trying to build with emscripten a program which uses std::vector and std::map and the compilation is successful. However, when I ran it on the web browser(firefox/chrome), UnboundTypeError was catched.


[03:21 :26.453] UnboundTypeError:无法调用intArrayToVector由于
未绑定的类型:Pi

[03:21:26.453] UnboundTypeError: Cannot call intArrayToVector due to unbound types: Pi

这里是c ++代码和HTML文件生成的JavaScript代码。

Here is c++ code and HTML file which uses generated javascript code.

test.cpp:

#include <vector>
#include <emscripten/bind.h>

using namespace emscripten;

std::vector<int> intArrayToVector(int* input, int num){
    std::vector<int> vec;
    for(int i=0; i<num; i++){
        int val = *(input+i);
        vec.push_back(val);
    }
    return vec;
}

EMSCRIPTEN_BINDINGS(test){
    register_vector<int>("VectorInt");
    function("intArrayToVector", &intArrayToVector, allow_raw_pointer<arg<0>>());
}

test.html:

test.html:

<html>
<body>
<script src="test.js"></script>
<script>
    var num = 6;
    var buf = Module._malloc(100);
    var arr = new Int8Array(num);
    for(var i=0; i<num; i++){
        arr[i] = i+2;
    }
    Module.HEAP8.set(arr, buf);
    var v = Module.intArrayToVector(buf, num);

    for(var i=0; i<num; i++){
        console.log(v.get(i));
    }
    Module._free(buf);
</script>
</body>
</html>

JavaScript代码由以下命令生成:

The javascript code was generated by the command below:


$ em ++ --bind test.cpp -o test.js

$ em++ --bind test.cpp -o test.js

解决这个问题?
谢谢任何帮助!

How can I solve this problem? Thank you for any help!

推荐答案

Embind不支持指向原始类型的指针Pi表示指向整数的指针。

Embind doesn't support pointers to primitive types. "Pi" means to "pointer to integer."

如果你总是知道数组的大小,你可以尝试传递数组作为一个const引用。例如

If you will always know the size of the array in advance, you could try passing the array as a const reference. e.g.

std::vector<int> intArrayToVector(const int (&input)[100])

参数,并使用 reinterpret_cast 将其视为指针。例如

Or you can cheat and use an integer parameter for the pointer and use reinterpret_cast to treat it as a pointer. e.g.

std::vector<int> intArrayToVector(uintptr_t input, size_t len) {
    const int* ptr = reinterpret_cast<int*>(input);
    ....
}

或者您可以使用 cwrap API ,它支持指向原始类型的指针。

Or you can use the cwrap API which does support pointers to primitive types.

这篇关于emscripten:我如何解决UnboundTypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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