Emscripten Bindings: How to create an accessible C/C++ array from Javascript?

…衆ロ難τιáo~ 提交于 2019-12-24 00:34:47

问题


I am using box2d and attempting to create a chain shape.

In order to create a chain shape or polygon shape I must pass an array of vectors in order to specify the geometry.

I do not see any documentation to help me accomplish this, and the notes about bindings here don't go into any detail about arrays.

How can I construct an array?


回答1:


I have solved this problem by using these (as yet undocumented) emscripten features.

Note that I am accessing the functions and values (like ALLOC_STACK and wrapPointer) out of the Box2D object simply because that is the scope where I have found them to be exposed. They are emscripten-specific values, so for a different project and/or build settings it would be different.

// an alternative method that may work (shorter, less obvious code) is 
// allocate([v1x,0,0,0,v1y,0,0,0,v2x,0,0,0,...], 'float', Box2D.ALLOC_STACK);
// 8 byte per vector * 4 vectors = 32 bytes of memory required 
var buffer = Box2D.allocate(32, 'float', Box2D.ALLOC_STACK);
Box2D.setValue(buffer, left, 'float'); // v1x
Box2D.setValue(buffer+4, bottom, 'float'); // v1y
Box2D.setValue(buffer+8, right, 'float'); // v2x
Box2D.setValue(buffer+12, bottom, 'float'); // v2y
Box2D.setValue(buffer+16, right, 'float'); // v3x
Box2D.setValue(buffer+20, top, 'float'); // v3y
Box2D.setValue(buffer+24, left, 'float'); // v4x
Box2D.setValue(buffer+28, top, 'float'); // v4y
var ptr_wrapped = Box2D.wrapPointer(buffer, Box2D.b2Vec2);
shape.CreateLoop(ptr_wrapped, 4);
body.CreateFixture(shape,0.0);


来源:https://stackoverflow.com/questions/12792486/emscripten-bindings-how-to-create-an-accessible-c-c-array-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!