diff --git a/src/mono/browser/browser.proj b/src/mono/browser/browser.proj
index f7429193002a60..63eb3f9883f44c 100644
--- a/src/mono/browser/browser.proj
+++ b/src/mono/browser/browser.proj
@@ -185,6 +185,7 @@
+
diff --git a/src/mono/browser/runtime/strings.ts b/src/mono/browser/runtime/strings.ts
index a596b4e35ef5a2..0eda60ba850a00 100644
--- a/src/mono/browser/runtime/strings.ts
+++ b/src/mono/browser/runtime/strings.ts
@@ -39,19 +39,20 @@ export function strings_init (): void {
export function stringToUTF8 (str: string): Uint8Array {
if (_text_encoder_utf8 === undefined) {
- const buffer = new Uint8Array(str.length * 2);
- Module.stringToUTF8Array(str, buffer, 0, str.length * 2);
+ const len = Module.lengthBytesUTF8(str);
+ const buffer = new Uint8Array(len);
+ Module.stringToUTF8Array(str, buffer, 0, len);
return buffer;
}
return _text_encoder_utf8.encode(str);
}
export function stringToUTF8Ptr (str: string): CharPtr {
- const bytes = (str.length + 1) * 2;
- const ptr = Module._malloc(bytes) as any;
- _zero_region(ptr, str.length * 2);
- const buffer = localHeapViewU8().subarray(ptr, ptr + bytes);
- buffer.set(stringToUTF8(str));
+ const size = Module.lengthBytesUTF8(str) + 1;
+ const ptr = Module._malloc(size) as any;
+ const buffer = localHeapViewU8().subarray(ptr, ptr + size);
+ Module.stringToUTF8Array(str, buffer, 0, size);
+ buffer[size - 1] = 0;
return ptr;
}
diff --git a/src/mono/browser/runtime/types/emscripten.ts b/src/mono/browser/runtime/types/emscripten.ts
index e2cc8e7c73ce67..bb630df0b32e8e 100644
--- a/src/mono/browser/runtime/types/emscripten.ts
+++ b/src/mono/browser/runtime/types/emscripten.ts
@@ -40,6 +40,7 @@ export declare interface EmscriptenModule {
UTF8ToString(ptr: CharPtr, maxBytesToRead?: number): string;
UTF8ArrayToString(u8Array: Uint8Array, idx?: number, maxBytesToRead?: number): string;
stringToUTF8Array(str: string, heap: Uint8Array, outIdx: number, maxBytesToWrite: number): void;
+ lengthBytesUTF8(str: string): number;
FS_createPath(parent: string, path: string, canRead?: boolean, canWrite?: boolean): string;
FS_createDataFile(parent: string, name: string, data: TypedArray, canRead: boolean, canWrite: boolean, canOwn?: boolean): string;
addFunction(fn: Function, signature: string): number;