Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 687
user3062135 Avatar asked Dec 03 '13 16:12

user3062135


1 Answers

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.

like image 68
William Avatar answered Oct 22 '22 00:10

William