PkmnLib/src/ScriptResolving/WASM/InterfaceMethods/WASMStringView.cpp

29 lines
1.5 KiB
C++
Raw Normal View History

2022-05-16 16:16:15 +00:00
#include "WASMStringView.hpp"
#include "WASMHelperFile.hpp"
wasm_func_t* ConstString_GetHash(WebAssemblyScriptResolver* resolver) {
return WasmHelpers::CreateFunc<u32, const ArbUt::StringView*>(
resolver, {[](WebAssemblyScriptResolver*, const ArbUt::StringView* sv) -> u32 { return sv->GetHash(); }});
}
wasm_func_t* ConstString_GetStr(WebAssemblyScriptResolver* resolver) {
return WasmHelpers::CreateFunc<i32, const ArbUt::StringView*>(
resolver, {[](WebAssemblyScriptResolver* resolver, const ArbUt::StringView* constString) -> i32 {
// To allow webassembly to access the C String, we need to allocate it inside it's memory.
// Length + 1 to make room for the '\0'
auto stringPointer = resolver->AllocateMemory(constString->Length() + 1, std::alignment_of<const char>());
// After we have the pointer to the memory allocated for the string, copy the string with specified length
// to it, then suffix it with the null byte to end it.
strncpy(reinterpret_cast<char*>(stringPointer.first), constString->c_str(), constString->Length());
stringPointer.first[constString->Length()] = '\0';
return stringPointer.second;
}});
}
void WASMStringView::Register(ArbUt::Dictionary<std::string, wasm_func_t*>& externs,
WebAssemblyScriptResolver* resolver) {
2022-05-22 11:00:53 +00:00
externs.Insert("const_string_get_hash", ConstString_GetHash(resolver));
externs.Insert("const_string_get_str", ConstString_GetStr(resolver));
2022-05-16 16:16:15 +00:00
}