embinding a templated class

61 views
Skip to first unread message

Ronny Nissengold

unread,
Aug 7, 2023, 9:34:24 AM8/7/23
to emscripten-discuss
Hi all!
here is a compiling example of a cpp templated class:

The question is is it possible to embind, for example for Foo<int> the member function
Foo<int>::add?
When trying the naiive approach it failed.
Thanks!
Ronny

template <class T>
class Foo
{
public:
Foo()
{
m_value = 0;
}
void add (T value)
{
m_value += value;
}
T m_value;
};

Brion Vibber

unread,
Aug 7, 2023, 11:42:16 AM8/7/23
to emscripte...@googlegroups.com
Sample code working for me with emcc 3.1.44:

#include <emscripten/bind.h>

using namespace emscripten;

template <class T>
class Foo
{
public:
Foo()
{
m_value = 0;
}
void add (T value)
{
m_value += value;
}
T m_value;
};


EMSCRIPTEN_BINDINGS(main) {
class_<Foo<int>>("Foo_int")
.constructor<>()
.function("add", &Foo<int>::add)
.property("value", &Foo<int>::m_value)
;

}

Sample use code runs in node 20.5.0:

let Module = require('./main.js');
Module().then((main) => {
let foo = new main.Foo_int();
console.log(`foo.value is ${foo.value}`);
console.log(`calling foo.add(15)`);
foo.add(15);
console.log(`foo.value is ${foo.value}`);
process.exit(0);
});


Makefile:
main.js : main.cpp
emcc -lembind -o main.js -O1 -s MODULARIZE=1 main.cpp

clean :
rm -f main.wasm
rm -f main.js

test :
node test.js


-- brion

--
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 emscripten-disc...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/emscripten-discuss/e2d7cdd8-2ff6-46fc-82af-6c3b9494a0cen%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages