-
Hello! I'm porting my code from Jurassic to jint. Ported classes are actually wrappers for CLR objects, but in some places can convert values to JsValue. I would like to avoid manually declaring JS properties and methods with FastSetProperty, so I don't inherit from ObjectInstance, but use the following code: public class ClrUnderlyingObject
{
[CanBeNull] public byte[] Bytes { get; set; }
}
public class JintObjectWrapper
{
private Engine _engine;
// js side
public JsValue bytes
{
get { return Underlying.Bytes != null ? _engine.Realm.Intrinsics.Uint8Array.Construct(Underlying.Bytes) : JsValue.Null; }
set { Underlying.Bytes = value?.AsUint8Array(); }
}
// clr side
internal ClrUnderlyingObject Underlying { get; } = new ClrUnderlyingObject();
// clr side
internal void SetEngine([NotNull] Engine engine)
{
_engine = engine ?? throw new ArgumentNullException(nameof(engine));
}
}
[TestMethod]
public void GithubJintHandler()
{
var engine = new Engine(options =>
{
options.SetWrapObjectHandler((e, target) =>
{
if (target is JintObjectWrapper jow)
jow.SetEngine(e); // intercept the instance and set the engine
return new ObjectWrapper(e, target);
});
});
var result = (JintObjectWrapper) engine
.SetValue("JintObjectWrapper", TypeReference.CreateTypeReference<JintObjectWrapper>(engine))
.Evaluate(@"
var bytes = new Uint8Array(6);
bytes[0] = 1;
bytes[1] = 2;
bytes[2] = 4;
bytes[3] = 8;
bytes[4] = 16;
bytes[5] = 32;
var res = new JintObjectWrapper();
res.bytes = bytes;
return res;")
.ToObject();
var expected = new byte[] { 1, 2, 4, 8, 16, 32 };
CollectionAssert.AreEqual(expected, result.Underlying.Bytes);
} Am I doing things wrong? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
I think ideally everything would just work without you manually creating wrappers. Jint tries hard to get the interop right and automatically convert between suitable types + allows you to create the converters needed. So I would just use |
Beta Was this translation helpful? Give feedback.
I think ideally everything would just work without you manually creating wrappers. Jint tries hard to get the interop right and automatically convert between suitable types + allows you to create the converters needed. So I would just use
ClrUnderlyingObject
directly as type injected to engine and ensure proper conversions when/if needed via type converters.