I have a question regarding the generated WASM code from my project.
I used the WebModule (Webassembly)
template in VS 2022 to create a fresh WASM project.
In that I put two classes beside the existing Program.cs
, a class Person
and a PersonFactory
:
[Export]
public class Person
{
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
[Export]
public class PersonFactory
{
private static int i = 0;
public PersonFactory() {}
public Person Create()
{
i++;
return new Person()
{
Name = $"Person {i}",
Birthdate = DateTime.UtcNow.AddMonths(-6).AddDays(i),
};
}
public IEnumerable<Person> CreateMany()
{
while (true)
{
yield return Create();
}
}
}
I then expected to be able to call this in the JS part of the index.html
file:
var factory = module.PersonFactory();
var person = factory.Create();
console.log(person);
var name = person.Name;
console.log(name);
var birthdate = person.Birthdate;
console.log(birthdate);
That however did not work as expected, as it said PersonFactory
was not found.
I looked in the generated .d.ts
to find that the factories constructor method is listed twice with a numbered name:
export declare class MyWebAssemblyModule {
instance: any;
module: any;
private constructor();
static instantiate(url?: string): Promise<MyWebAssemblyModule>;
RemObjects_Elements_System_Attribute(): RemObjects_Elements_System_Attribute;
//... a lot more here ...
RemObjects_Elements_System___Global_Write(a:number, b:number, c:number, d:number): number;
Person(): Person;
PersonFactory0(): PersonFactory;
PersonFactory1(): PersonFactory;
Program(): Program;
}
So, first of all, why do I have PersonFactory0()
and PersonFactory1()
here?
Also, the generated person interface does not have the birthdate listed:
export interface Person extends RemObjects_Elements_System_Object{
Name: string;
}
When I used the PersonFactory0()
method I got the factory, and it also created a person.
The first console.log
call logged the object. The object however, when expanded in the browsers devtools console, showed undefined
for both Name
and Birthdate
(the birthdate property seems to be available here, but not a value for it).
Although, the correct Name
was logged in the second log call. The third log call shows undefined when I wanted to log the Birthdate
.
Can you confirm what happens here? I would guess that after the MyWebAssemblyModule.instantiate(
callback returns, the instance of person is removed from the islands’ GC in the WASM runtime, and as such I can’t access the values of the properties anymore in the logged object instance, so they are showing undefined here?
Will the instance be kept when I hold a reference in the JS part?
Also, I would guess the Datetime type isn’t (yet) mapped to something available in the JS runtime part?
How would I pass these types along? Should I create a specific wrapping type that passes it along as a string or number and parse that to a JS date object, or would that be something that your wrapping JS code should do?