On Tue, Jul 8, 2014 at 11:36 PM, Juha Järvi <[email protected]> wrote:
> Hi,
>
> I've got a nasty compressed list structure in C++ and would like to
> iterate through it from JavaScript using a for-each style method, passing a
> JavaScript function as a callback. My C++ test code is:
>
> #include <emscripten.h>
> #include <emscripten/bind.h>
>
> class Iterable {
> public:
> void each(void(*fn)(int)) const {
> fn(42);
> }
> };
>
> EMSCRIPTEN_BINDINGS(test) {
> emscripten::class_<Iterable>("Iterable")
> .constructor<>()
> .function("each",&Iterable::each,emscripten::allow_raw_pointers());
> }
>
> Called from JavaScript like:
>
> i=new Module.Iterable();
> i.each(function(x) {console.log(x);})
>
> However it gives an error:
>
> UnboundTypeError: Cannot call Iterable.each due to unbound types: PFviE
>
> I understand that the callback function needs wrapping using
> Runtime.addFunction and embind doesn't handle things automatically in this
> case for example because lifetime of the pointer is unclear, but what would
> be the simplest way to make this work, preferably so that if some C++
> function returns an Iterable to JavaScript, its prototype would already
> have an each() method with all the required wrappers?
>
I thought about this a little more and I think the best you can do in this
case is something like:
.function("each", &each_wrapper)
where each_wrapper is defined as:
static val lastVal = val::undefined();
void each_wrapper(Iterable& iterable, const val& v) {
lastVal = v;
iterable.each([](int i) {
lastVal(i);
});
lastVal = val::undefined();
}
> Best regards,
> -Juha
>
> --
> You received this message because you are subscribed to the Google Groups
> "emscripten-discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>
--
Chad Austin
Technical Director, IMVU
http://engineering.imvu.com <http://www.imvu.com/members/Chad/>
http://chadaustin.me
--
You received this message because you are subscribed to the Google Groups
"emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.