Я преследовал эту цель уже пару месяцев, но, похоже, не могу скомпилировать ее в Wasm в браузере, без сервера, только в клиенте. Я надеялся выяснить, почему. моя последняя ошибка:
Error initializing compiler. Check console for details. Failed to execute 'postMessage' on 'Worker': SharedArrayBuffer transfer requires self.crossOriginIsolated.
Если эта цель невозможна с тем, что я сейчас делаю, а именно с веб-контейнерами, подскажите мне, пожалуйста, какой-нибудь пакет или что-нибудь еще, что может скомпилировать C++ в WASM в браузере, только на стороне клиента. Я пробовал множество, таких как emception, jupyter и cib.
для кода (дамп кода)
document.addEventListener('DOMContentLoaded', () => {
(async () => {
try { // Add a try block here
const { WebContainer } = await import('https://cdn.jsdelivr.net/npm/@webcontai ... t/index.js');
await WebContainer.boot();
const out = document.getElementById('out');
const codeEl = document.getElementById('code-editor');
const compiler = new Worker('./compile-worker.js', { type: 'module' });
const runner = new Worker('./run-worker.js', { type: 'module' });
compiler.onmessage = (e) => {
if (e.data.type === 'error') {
out.textContent += 'Compile error: ' + e.data.message + '\n';
return;
}
out.textContent += 'Running...\n';
runner.onmessage = (m) => {
const { stdout, stderr, exitCode } = m.data || {};
out.textContent += stdout + (stderr ? '\n[stderr]\n' + stderr : '') + '\n[exit ' + exitCode + ']';
};
runner.postMessage({ type: 'runWasi', wasm: e.data.wasm });
};
document.getElementById('run').onclick = () => {
out.textContent = 'Compiling...\n';
compiler.postMessage({ code: codeEl.value });
};
} catch (error) { // And a catch block here
console.error("Error during WebContainer initialization or setup:", error);
const out = document.getElementById('out');
if (out) {
out.textContent = "Error initializing compiler. Check console for details. " + error.message;
}
}
})();
// your editor helpers unchanged
const INDENT = ' ';
const normalizeQuote = (ch) => (ch === '‘' || ch === '’') ? "'" : (ch === '“' || ch === '”') ? '"' : ch;
document.addEventListener('keydown', (e) => {
const ta = e.target;
if (!(ta instanceof HTMLTextAreaElement) || !ta.matches('.code-editor')) return;
const nextChar = () => ta.value.slice(ta.selectionStart, ta.selectionStart + 1);
const key = normalizeQuote(e.key);
const next = normalizeQuote(nextChar());
if ('}])\'"'.includes(key) && next === key) {
e.preventDefault();
ta.selectionStart = ta.selectionEnd = ta.selectionStart + 1;
return;
}
const pairs = { '{': '}', '[': ']', '(': ')', '"': '"', "'": "'" };
if (pairs[key]) {
e.preventDefault();
const { selectionStart: s, selectionEnd: epos, value } = ta;
const open = key, close = pairs[key];
if (s !== epos) {
const sel = value.slice(s, epos);
ta.value = value.slice(0, s) + open + sel + close + value.slice(epos);
ta.selectionStart = s + 1;
ta.selectionEnd = epos + 1;
} else {
ta.value = value.slice(0, s) + open + close + value.slice(epos);
ta.selectionStart = ta.selectionEnd = s + 1;
}
return;
}
if (e.key === 'Tab') {
e.preventDefault();
const { selectionStart: s, selectionEnd: epos, value } = ta;
ta.value = value.slice(0, s) + INDENT + value.slice(epos);
ta.selectionStart = ta.selectionEnd = s + INDENT.length;
return;
}
if (e.key === 'Enter') {
e.preventDefault();
const { selectionStart: s, selectionEnd: epos, value } = ta;
const lineStart = value.lastIndexOf('\n', s - 1) + 1;
const line = value.slice(lineStart, s);
const baseIndent = (line.match(/^[ \t]*/) || [''])[0];
const trimmed = line.trimEnd();
const addBlockIndent = /[{:]$/.test(trimmed) ? INDENT : '';
const insert = '\n' + baseIndent + addBlockIndent;
const pos = s + insert.length;
ta.value = value.slice(0, s) + insert + value.slice(epos);
ta.selectionStart = ta.selectionEnd = pos;
if (ta.value.slice(pos, pos + 1) === '}') {
const fix = '\n' + baseIndent;
ta.value = ta.value.slice(0, pos) + fix + ta.value.slice(pos);
ta.selectionStart = ta.selectionEnd = pos;
}
}
});
});
Это hello.js.
это мой compile-worker.js
import { WebContainer } from '@webcontainer/api';
let wc;
self.onmessage = async (e) => {
const code = e.data?.code || '#include \nint main(){std::cout
Подробнее здесь: https://stackoverflow.com/questions/798 ... dificultys
C++ для WASM в трудностях на стороне клиента браузера ⇐ Html
Программисты Html
-
Anonymous
1762895763
Anonymous
Я преследовал эту цель уже пару месяцев, но, похоже, не могу скомпилировать ее в Wasm в браузере, без сервера, только в клиенте. Я надеялся выяснить, почему. моя последняя ошибка:
Error initializing compiler. Check console for details. Failed to execute 'postMessage' on 'Worker': SharedArrayBuffer transfer requires self.crossOriginIsolated.
Если эта цель невозможна с тем, что я сейчас делаю, а именно с веб-контейнерами, подскажите мне, пожалуйста, какой-нибудь пакет или что-нибудь еще, что может скомпилировать C++ в WASM в браузере, только на стороне клиента. Я пробовал множество, таких как emception, jupyter и cib.
для кода (дамп кода)
document.addEventListener('DOMContentLoaded', () => {
(async () => {
try { // Add a try block here
const { WebContainer } = await import('https://cdn.jsdelivr.net/npm/@webcontainer/api/dist/index.js');
await WebContainer.boot();
const out = document.getElementById('out');
const codeEl = document.getElementById('code-editor');
const compiler = new Worker('./compile-worker.js', { type: 'module' });
const runner = new Worker('./run-worker.js', { type: 'module' });
compiler.onmessage = (e) => {
if (e.data.type === 'error') {
out.textContent += 'Compile error: ' + e.data.message + '\n';
return;
}
out.textContent += 'Running...\n';
runner.onmessage = (m) => {
const { stdout, stderr, exitCode } = m.data || {};
out.textContent += stdout + (stderr ? '\n[stderr]\n' + stderr : '') + '\n[exit ' + exitCode + ']';
};
runner.postMessage({ type: 'runWasi', wasm: e.data.wasm });
};
document.getElementById('run').onclick = () => {
out.textContent = 'Compiling...\n';
compiler.postMessage({ code: codeEl.value });
};
} catch (error) { // And a catch block here
console.error("Error during WebContainer initialization or setup:", error);
const out = document.getElementById('out');
if (out) {
out.textContent = "Error initializing compiler. Check console for details. " + error.message;
}
}
})();
// your editor helpers unchanged
const INDENT = ' ';
const normalizeQuote = (ch) => (ch === '‘' || ch === '’') ? "'" : (ch === '“' || ch === '”') ? '"' : ch;
document.addEventListener('keydown', (e) => {
const ta = e.target;
if (!(ta instanceof HTMLTextAreaElement) || !ta.matches('.code-editor')) return;
const nextChar = () => ta.value.slice(ta.selectionStart, ta.selectionStart + 1);
const key = normalizeQuote(e.key);
const next = normalizeQuote(nextChar());
if ('}])\'"'.includes(key) && next === key) {
e.preventDefault();
ta.selectionStart = ta.selectionEnd = ta.selectionStart + 1;
return;
}
const pairs = { '{': '}', '[': ']', '(': ')', '"': '"', "'": "'" };
if (pairs[key]) {
e.preventDefault();
const { selectionStart: s, selectionEnd: epos, value } = ta;
const open = key, close = pairs[key];
if (s !== epos) {
const sel = value.slice(s, epos);
ta.value = value.slice(0, s) + open + sel + close + value.slice(epos);
ta.selectionStart = s + 1;
ta.selectionEnd = epos + 1;
} else {
ta.value = value.slice(0, s) + open + close + value.slice(epos);
ta.selectionStart = ta.selectionEnd = s + 1;
}
return;
}
if (e.key === 'Tab') {
e.preventDefault();
const { selectionStart: s, selectionEnd: epos, value } = ta;
ta.value = value.slice(0, s) + INDENT + value.slice(epos);
ta.selectionStart = ta.selectionEnd = s + INDENT.length;
return;
}
if (e.key === 'Enter') {
e.preventDefault();
const { selectionStart: s, selectionEnd: epos, value } = ta;
const lineStart = value.lastIndexOf('\n', s - 1) + 1;
const line = value.slice(lineStart, s);
const baseIndent = (line.match(/^[ \t]*/) || [''])[0];
const trimmed = line.trimEnd();
const addBlockIndent = /[{:]$/.test(trimmed) ? INDENT : '';
const insert = '\n' + baseIndent + addBlockIndent;
const pos = s + insert.length;
ta.value = value.slice(0, s) + insert + value.slice(epos);
ta.selectionStart = ta.selectionEnd = pos;
if (ta.value.slice(pos, pos + 1) === '}') {
const fix = '\n' + baseIndent;
ta.value = ta.value.slice(0, pos) + fix + ta.value.slice(pos);
ta.selectionStart = ta.selectionEnd = pos;
}
}
});
});
Это hello.js.
это мой compile-worker.js
import { WebContainer } from '@webcontainer/api';
let wc;
self.onmessage = async (e) => {
const code = e.data?.code || '#include \nint main(){std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79817127/c-to-wasm-in-browser-client-side-dificultys[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия