Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c# - Pass an object to a function in jint and return a value

I'm attempting to pass an object to a javascript function via jint and return a value. But it doesn't seem to work. Here is what I have tried so far -

Error -

Jint.Runtime.JavaScriptException: 'obj is undefined'

Using the following code -

var carObj = JsonSerializer.Serialize(car);  

var engine = new Jint.Engine();
engine.SetValue("obj", carObj);

var value = engine
           .Execute("const result = (function car(obj) { const type = obj.Type; return type;})()")
           .GetValue("result");
question from:https://stackoverflow.com/questions/65915909/pass-an-object-to-a-function-in-jint-and-return-a-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As shown in the docs, you should pass your POCO car directly to Jint.Engine rather than trying to serialize it to JSON. Jint will use reflection to access its members.

Thus your code can be rewritten as follows:

var value = new Jint.Engine()  // Create the Jint engine
    .Execute("function car(obj) { const type = obj.Type; return type;}") // Define a function car() that accesses the Type field of the incoming obj and returns it.
    .Invoke("car", car);  // Invoke the car() function on the car POCO, and return its result.

Or equivalently as:

var value = new Jint.Engine()
    .SetValue("obj", car) // Define a "global" variable "obj"
    .Execute("const result = (function car(obj) { const type = obj.Type; return type;})(obj)") // Define the car() function, call it with "obj", and set the value in "result"
    .GetValue("result"); // Get the evaluated value of "result"

Or

var value = new Jint.Engine()  // Create the Jint engine
    .SetValue("obj", car) // Define a "global" variable "obj"
    .Execute("function car(obj) { const type = obj.Type; return type;}; car(obj);") // Define the car() function, and call it with "obj".
    .GetCompletionValue();  // Get the last evaluated statement completion value            

Here I am assuming that car is a POCO that has a string property Type, e.g.

var car = new 
{
    Type = "studebaker convertible",
};

Demo fiddle here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...