Skip to content

Commit

Permalink
Fix js string marshaling
Browse files Browse the repository at this point in the history
  • Loading branch information
lewing committed Apr 13, 2024
1 parent 4cca6f1 commit 620386b
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/mono/browser/browser.proj
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@
<EmccExportedRuntimeMethod Include="getValue" />
<EmccExportedRuntimeMethod Include="UTF8ToString" />
<EmccExportedRuntimeMethod Include="UTF8ArrayToString" />
<EmccExportedRuntimeMethod Include="lengthBytesUTF8" />
<EmccExportedRuntimeMethod Include="stringToUTF8Array" />
<EmccExportedRuntimeMethod Include="FS_createPath" />
<EmccExportedRuntimeMethod Include="FS_createDataFile" />
Expand Down
15 changes: 8 additions & 7 deletions src/mono/browser/runtime/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
1 change: 1 addition & 0 deletions src/mono/browser/runtime/types/emscripten.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 620386b

Please sign in to comment.