Skip to content

[embind] Export embind exports as ESM exports for MODULARIZE=instance. #23404

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/lib/libembind.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ var LibraryEmbind = {
$PureVirtualError: class extends Error {},
$GenericWireTypeSize: {{{ 2 * POINTER_SIZE }}},
#if EMBIND_AOT
$InvokerFunctions: '<<< EMBIND_AOT_OUTPUT >>>',
$InvokerFunctions: '<<< EMBIND_AOT_INVOKERS >>>',
#endif
// If register_type is used, emval will be registered multiple times for
// different type id's, but only a single type object is needed on the JS side
Expand Down
15 changes: 13 additions & 2 deletions src/lib/libembind_gen.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ var LibraryEmbind = {
},
$FunctionDefinition__deps: ['$createJsInvoker', '$createJsInvokerSignature', '$emittedFunctions'],
$FunctionDefinition: class {
hasPublicSymbol = true;
constructor(name, returnType, argumentTypes, functionIndex, thisType = null, isNonnullReturn = false, isAsync = false) {
this.name = name;
this.returnType = returnType;
Expand Down Expand Up @@ -154,6 +155,7 @@ var LibraryEmbind = {
}
},
$ClassDefinition: class {
hasPublicSymbol = true;
constructor(typeId, name, base = null) {
this.typeId = typeId;
this.name = name;
Expand Down Expand Up @@ -265,6 +267,7 @@ var LibraryEmbind = {
}
},
$ConstantDefinition: class {
hasPublicSymbol = true;
constructor(type, name) {
this.type = type;
this.name = name;
Expand All @@ -275,6 +278,7 @@ var LibraryEmbind = {
}
},
$EnumDefinition: class {
hasPublicSymbol = true;
constructor(typeId, name) {
this.typeId = typeId;
this.name = name;
Expand Down Expand Up @@ -451,14 +455,21 @@ var LibraryEmbind = {

print() {
const out = ['{\n'];
const publicSymbols = [];
for (const def of this.definitions) {
if (def.hasPublicSymbol) {
publicSymbols.push(def.name);
}
if (!def.printJs) {
continue;
}
def.printJs(out);
}
out.push('}')
console.log(out.join(''));
out.push('}\n');
console.log(JSON.stringify({
'invokers': out.join(''),
publicSymbols,
}));
}
},

Expand Down
26 changes: 26 additions & 0 deletions test/modularize_instance_embind.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <stdio.h>
#include <emscripten.h>
#include <emscripten/bind.h>

using namespace emscripten;

void foo() {
printf("foo\n");
}

struct Bar {
void print() {
printf("bar\n");
}
};

int main() {
printf("main\n");
}

EMSCRIPTEN_BINDINGS(xxx) {
function("foo", &foo);
class_<Bar>("Bar")
.constructor<>()
.function("print", &Bar::print);
}
18 changes: 18 additions & 0 deletions test/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -9627,6 +9627,24 @@ def test_modularize_instance(self, args):

self.assertContained('main1\nmain2\nfoo\nbar\nbaz\n', self.run_js('runner.mjs'))

def test_modularize_instance_embind(self):
self.run_process([EMCC, test_file('modularize_instance_embind.cpp'),
'-sMODULARIZE=instance',
'-lembind',
'-sEMBIND_AOT',
'-o', 'modularize_instance_embind.mjs'])

create_file('runner.mjs', '''
import init, { foo, Bar } from "./modularize_instance_embind.mjs";
await init();
foo();
const bar = new Bar();
bar.print();
bar.delete();
''')

self.assertContained('main\nfoo\nbar\n', self.run_js('runner.mjs'))


# Generate tests for everything
def make_run(name, emcc_args, settings=None, env=None,
Expand Down
20 changes: 18 additions & 2 deletions tools/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -1380,6 +1380,9 @@ def limit_incoming_module_api():
settings.REQUIRED_EXPORTS.append('__getTypeName')
if settings.PTHREADS or settings.WASM_WORKERS:
settings.REQUIRED_EXPORTS.append('_embind_initialize_bindings')
# Needed to assign the embind exports to the ES exports.
if settings.MODULARIZE == 'instance':
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$addOnPostCtor']

if options.emit_tsd:
settings.EMIT_TSD = True
Expand Down Expand Up @@ -2053,9 +2056,22 @@ def phase_emit_tsd(options, wasm_target, js_target, js_syms, metadata):
def phase_embind_aot(options, wasm_target, js_syms):
out = run_embind_gen(options, wasm_target, js_syms, {})
if DEBUG:
write_file(in_temp('embind_aot.js'), out)
write_file(in_temp('embind_aot.json'), out)
out = json.loads(out)
src = read_file(final_js)
src = do_replace(src, '<<< EMBIND_AOT_OUTPUT >>>', out)
src = do_replace(src, '<<< EMBIND_AOT_INVOKERS >>>', out['invokers'])
if settings.MODULARIZE == 'instance':
# Add ES module exports for the embind exports.
decls = '\n'.join([f'export var {name};' for name in out['publicSymbols']])
# Assign the runtime exports from Module to the ES export.
assigns = '\n'.join([f'{name} = Module[\'{name}\'];' for name in out['publicSymbols']])
exports = f'''
// start embind exports
function assignEmbindExports() {{ {assigns} }};
addOnPostCtor(assignEmbindExports);
{decls}
// end embind exports'''
src += exports
write_file(final_js, src)


Expand Down