Dav*_*542 10 javascript c c++ rust webassembly
我想知道是否可以使用 C(或 C++ 或 Rust)和 javascript 对共享数据对象执行 CRUD 操作。使用最基本的示例,这里将是一个示例或每个操作:
#include <stdio.h>
typedef struct Person {
int age;
char* name;
} Person;
int main(void) {
// init
Person* sharedPersons[100];
int idx=0;
// create
sharedPersons[idx] = (Person*) {12, "Tom"};
// read
printf("{name: %s, age: %d}", sharedPersons[idx]->name, sharedPersons[idx]->age);
// update
sharedPersons[idx]->age = 11;
// delete
sharedPersons[idx] = NULL;
}
Run Code Online (Sandbox Code Playgroud)
然后,我希望能够在 Javascript 中做完全相同的事情,并且都能够写入同一个共享sharedPersons
对象。这怎么可能?或者设置是否需要类似于“主从”,其中一个只需要将信息传递给另一个,然后主执行所有相关操作?我希望有一种方法可以对 webassembly 中的共享数据对象进行 CRUD,任何帮助将不胜感激。
作为参考:https : //rustwasm.github.io/wasm-bindgen/contributing/design/js-objects-in-rust.html
让我们在 C 中创建对象并返回它:
typedef struct Person {
int age;
char* name;
} Person;
Person *get_persons(void) {
Person* sharedPersons[100];
return sharedPersons;
}
Run Code Online (Sandbox Code Playgroud)
您也可以在 JS 中创建对象,但它更难。稍后我会回到这个话题。
为了让 JS 获取对象,我们定义了一个函数 ( get_persons
) 来返回(指向)它。在这种情况下,它是一个数组,但当然它可以是单个对象。问题是,必须有一个函数可以从 JS 中调用并提供对象。
emcc \
-s "SINGLE_FILE=1" \
-s "MODULARIZE=1" \
-s "ALLOW_MEMORY_GROWTH=1" \
-s "EXPORT_NAME=createModule" \
-s "EXPORTED_FUNCTIONS=['_get_persons', '_malloc', '_free']" \
-s "EXPORTED_RUNTIME_METHODS=['cwrap', 'setValue', 'getValue', 'AsciiToString', 'writeStringToMemory']" \
-o myclib.js
person.c
Run Code Online (Sandbox Code Playgroud)
我不记得为什么我们在 中有一个前导下划线_get_persons
,但这就是 Emscripten 的工作方式。
const createModule = require('./myclib');
let myclib;
let Module;
export const myclibRuntime = createModule().then((module) => {
get_persons: Module.cwrap('get_persons', 'number', []),
});
Run Code Online (Sandbox Code Playgroud)
这样做是创建一个get_persons()
JS 函数,它是 Cget_persons()
函数的包装器。JS 函数的返回值是“数字”。Emscripten 知道 Cget_persons()
函数返回一个指针,包装器会将该指针转换为 JS 编号。(WASM 中的指针是 32 位的。)
const persons = get_persons();
Module.getValue(persons, 'i32'); // Returns the age of the first person
Module.AsciiToString(Module.getValue(persons + 4, 'i32')); // Name of first person
// Set the second person to be "Alice", age 18
const second_person = persons + 8;
Module.setValue(second_person, 18, 'i32');
const buffer = Module._malloc(6); // Length of "Alice" plus the null terminator
Module.writeStringToMemory("Alice", buffer);
Module.setValue(second_person + 4, buffer, 'i32');
Run Code Online (Sandbox Code Playgroud)
这是一种相当低级的方法,尽管似乎还有更低级的方法。正如其他人所建议的那样,可能有更高级别的工具可以帮助 C++ 和 Rust。
您可以在 JS 中通过使用_malloc()
(并使用释放它们_free()
)来创建对象,就像我们对上面的字符串所做的那样,然后将它们的指针传递给 C 函数。但是,正如我所说,在 C 中创建它们可能更容易。在任何情况下,任何_malloc()
ed 最终都必须被释放(因此上面的字符串创建是不完整的)。该FinalizationRegistry可以在这方面帮助。