Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

javascript - emscripten: How can I solve 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: Cannot call intArrayToVector due to unbound types: Pi

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:

<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>

The javascript code was generated by the command below:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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])

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);
    ....
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...