Is there any advantage/disadvantage to using function delegates over lambdas in a collection? - visual-c++

I am at that really boring part in the development of my library, where I want to construct a class based on a windows message identifier and the WPARAM and LPARAM arguments. The prototype for such functions is trivial:
boost::shared_ptr<EventArgs>(const UINT& _id, const WPARAM& _w, const LPARAM& _l);
For each windows message, I will have a function of this nature.
Now, what I am currently doing is using the FastDelegate library to do my delegates. These are stored in a map thusly:
typedef fastdelegate::FastDelegate3<const UINT&, const WPARAM&, const LPARAM&, boost::shared_ptr<EventArgs> > delegate_type;
typedef std::map<int, delegate_type> CreatorMap;
And when a windows message needs to have an EventArg-derived class created, it's a simple case of looking up the appropriate delegate, invoking it and returning the newly-created instance nicely contained in a shared_ptr.
boost::shared_ptr<EventArgs> make(const UINT& _id, const WPARAM& _w, const LPARAM& _l) const
{
MsgMap::const_iterator cit(m_Map.find(_id));
assert(cit != m_Map.end());
boost::shared_ptr<EventArgs> ret(cit->second(_w, _l));
return ret;
}; // eo make
All is working fine. But then I was thinking, rather than having all these delegates around, why not take advantage of lambdas in C++0x? So, I quickly prototyped the following:
typedef std::map<int, std::function<boost::shared_ptr<EventArgs>(const WPARAM&, const LPARAM&)> > MapType;
typedef MapType::iterator mit;
MapType map;
map[WM_WHATEVER] = [](const WPARAM& _w, const LPARAM& _l) { /* create appropriate eventargs class given parameters */ };
map[WM_ANOTHER] = ....;
// and so on
Once again, it's simple to look up and invoke:
mit m = map.find(WM_PAINT);
boost::shared_ptr<EventArgs> e(m->second(_wParam, _lParam));
// dispatch e
Is there an advantage to using lambdas in this way? I know the overhead of looking up the right delegate/lambda will be the same (as both types of map are keyed with an int), but I am aiming to dispatch my messages from the wndProc in my nice C++ friendly-way as efficiently as possible. My gut-feeling is that lambdas will be faster, but unfortunately i lack the experience in understanding compiler-optimizations to make a judgement call on this, hence my question here :) Oh, and in keeping with the topic of the question, are there any gotchas/something I haven't thought about?

I see two real differences here:
The first is how you store the callback: Either the fast-delegate or std::function. The latter is based on boost::function, and fast delegates were specifically designed to outperform those. However, std::function is standard conforming, while fast delegates are not.
The other difference is the way you setup your code, and I see a clear advantage for lambdas here. You can write the actual code exactly where it matters, you don't need to define a separate function that only serves a niche-purpose.
If you want raw speed - fast-delegates probably win (but you should benchmark, if that is an argument), but if you want readability and standard conformity, go with std::function and lambdas.

Related

How to pass information into Unreal Engine from outside source

The Problem:
I want a high quality visualization of a simulation that I've built and runs on another application. Unreal Engine 4 has models that work, and renders nicely enough to fill my needs. The only problem, is I need to tell a running instance of an Unreal Engine project some of the information that my simulation is creating, like moving objects.
Potential solutions:
rpc plugin?
I'm reasonably familiar with grpc, and my simulation is set up so send and receive grpc messages, but I don't know how to implement grpc through unreal_engine. A couple others on the interweb have written rpc plugins, which might work for my needs. For example...
https://github.com/PaddleCreekGames/Proto3RPC_UE4
However, no idea how to take that pile of work done and actually use what I want. Needless to say, the documentation of that specific project is unfriendly to a user who didn't write it.
Something else?
If you have any ideas, or if you've historically passed information to unreal engine a specific way, any pointers in the right direction/code snippets/links to stuff I may have missed would be greatly appreciated.
I had the same question with theodox,
if the input doesn't have to happen instantly/in real-time.
You may for example update a parameter file for you simulation and read the parameters in your unreal engine application.
Here is an example to create the readFile bluemix function to read and parse an external JSON file:
in /Source/[Project name]/MyBlueprintFunctionLibrary.h, define output struct and function header
USTRUCT(BlueprintType)
struct FResultStruct
{
GENERATED_USTRUCT_BODY()
UPROPERTY(EditAnywhere,BlueprintReadWrite,Category = "Result Struct")
float fieldname1;
UPROPERTY(EditAnywhere,BlueprintReadWrite,Category = "Result Struct")
FString fieldname2;
//Constructor
FResultStruct()
{
fieldname1 = 0;
fieldname2 = "string";
}
};
UCLASS()
class EXPERIMENTALPROJECT_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "MyBPLibrary")
static FResultStruct ReadFile(FString fileName);
};
in /Source/[Project name]/MyBlueprintFunctionLibrary.cpp implement your parameter file parser, for example:
// Read the results file
FResultStruct UMyBlueprintFunctionLibrary::ReadFile(FString fileName)
{
FString saveFilePath = FPaths::ConvertRelativePathToFull(FPaths::GameDir());
fileName = saveFilePath + fileName;
FResultStruct Result;
FString jsonString;
FFileHelper::LoadFileToString(jsonString, *fileName);
TSharedPtr<FJsonObject> JsonParsed;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(jsonString);
if (FJsonSerializer::Deserialize(JsonReader, JsonParsed))
{
Result.fieldname1 = JsonParsed->GetNumberField("fieldname1");
Result.fieldname2 = JsonParsed->GetStringField("fieldname2");
}
return Result;
}
And in your unreal engine blueprint you can call this file reading function and use its parsed content in your application:
example
If you need live input, you may need to create HUD in UE4 and create input fields for all your parameters, that's more labor intensive imo.

Node.js, EventEmitter of why using it

I have a question about events.EventEmitter in Node.js, why use it? What is the difference with example 1 and example 2? I find them identical, are they? When is it practical to use it?
let events = require("events");
let util = require("util");
let eventEmitter = new events.EventEmitter();
Example 1 with the EventEmitter:
let Student = function(name) {
this.name = name;
}
util.inherits(Student, events.EventEmitter);
let student_max = new Student('max');
student_max.on('scored', function(points) {
if (points > 90) {
points = points + ' wow you scored more than 90'
}
console.log(`${this.name} ${points} points`);
})
student_max.emit('scored',95);
Example 2 without EventEmitter
let Student2 = function(name) {
this.name = name;
this.score = function(str,points) {
if (str!=='scored') {
return;
}
if (points > 90) {
points = points + ' wow you scored more than 90'
}
console.log(`${this.name} ${points} points`);
}
}
let student_lenny = new Student2('Lenny');
student_lenny.score('scored',95);
The first example subclasses an event emitter and then uses that event emitter to implement some functionality. That means that anyone else can take one of your student_max objects and register an event listener for the scored message or they could even emit a scored message themselves. You could then very easily use the eventEmitter functionality to extend to other events that occurred in your object and then any third party could observe or trigger those events too. eventEmitter is a standardized way of exposing event based functionality. You can accomplish things with an eventEmitter by designing your own notification schemes, but it is often better to build on a standard scheme that lots of developers already know and that has a fair amount of functionality already built in.
Your second example as currently coded accomplishes the same thing, but is not as extensible. For example, if you wanted to know anything a score happens, you would have to subclass the object and override the score method rather than just adding a listener to an event using the well-established eventEmitter interface. If you didn't create the object yourself (which makes it hard to subclass), then you'd have to monkey-patch the score method in order to observe it.
what is the difference of the example1 to example2
It's an architectural difference that affects both how outside agents interact with these objects and how extensible they are in the future.
The use of the eventEmitter in example1 is very extensible and makes it easy to add future events to the object using the eventEmitter features or for outside agents to monitor or trigger events using a standardized interface. So, the difference is not in exactly what the code you show achieves, but in how it is architected and thus how extensible it would be in the future or how outside code could interact with your object
When is it practical to use it?
You would think about using an eventEmitter object pretty much anytime you want outside parties to be able to observe events or trigger events on your object in a lightweight and easy way. It's a pre-built system for that and is often better than inventing your own callback notification scheme. And sometimes, it is useful even for your own implementation when you aren't trying to enable outside interactions.

Flux - Isn't it a bad practice to include the dispatcher instance everywhere?

Note: My question is about the way of including/passing the dispatcher instance around, not about how the pattern is useful.
I am studying the Flux Architecture and I cannot get my head around the concept of the dispatcher (instance) potentially being included everywhere...
What if I want to trigger an Action from my Model Layer? It feels weird to me to include an instance of an object in my Model files... I feel like this is missing some injection pattern...
I have the impression that the exact PHP equivalent is something (that feels) horrible similar to:
<?php
$dispatcher = require '../dispatcher_instance.php';
class MyModel {
...
public function someMethod() {
...
$dispatcher->...
}
}
I think my question is not exactly only related to the Flux Architecture but more to the NodeJS "way of doing things"/practices in general.
TLDR:
No, it is not bad practice to pass around the instance of the dispatcher in your stores
All data stores should have a reference to the dispatcher
The invoking/consuming code (in React, this is usually the view) should only have references to the action-creators, not the dispatcher
Your code doesn't quite align with React because you are creating a public mutable function on your data store.
The ONLY way to communicate with a store in Flux is via message passing which always flows through the dispatcher.
For example:
var Dispatcher = require('MyAppDispatcher');
var ExampleActions = require('ExampleActions');
var _data = 10;
var ExampleStore = assign({}, EventEmitter.prototype, {
getData() {
return _data;
},
emitChange() {
this.emit('change');
},
dispatcherKey: Dispatcher.register(payload => {
var {action} = payload;
switch (action.type) {
case ACTIONS.ADD_1:
_data += 1;
ExampleStore.emitChange();
ExampleActions.doThatOtherThing();
break;
}
})
});
module.exports = ExampleStore;
By closing over _data instead of having a data property directly on the store, you can enforce the message passing rule. It's a private member.
Also important to note, although you can call Dispatcher.emit() directly, it's not a good idea.
There are two main reasons to go through the action-creators:
Consistency - This is how your views and other consuming code interacts with the stores
Easier Refactoring - If you ever remove the ADD_1 action from your app, this code will throw an exception rather than silently failing by sending a message that doesn't match any of the switch statements in any of the stores
Main Advantages to this Approach
Loose coupling - Adding and removing features is a breeze. Stores can respond to any event in the system with by adding one line of code.
Less complexity - One way data flow makes wrapping head around data flow a lot easier. Less interdependencies.
Easier debugging - You can debug every change in your system with a few lines of code.
debugging example:
var MyAppDispatcher = require('MyAppDispatcher');
MyAppDispatcher.register(payload => {
console.debug(payload);
});

What language level support (if any) does Swift have for asynchronous programming?

Asynchronous programming is a must for responsive user interfaces when application have to communicate over unpredictable networks (e.g. smart phone applications). The user interface must remain responsive while waiting for results to come back from servers somewhere over the internet.
In most languages, the application programmer has to implement their own state machines (maybe using closures) to respond to asynchronous callbacks and/or coordinate multiply threads using locks.
Both of these are very error prone and not for the fait hearted!
(c# introduced the async keyword to help with this, only time (at least 5 years) will tell if it is a good solution.)
Does Swift have any built in support to assist the writing of asynchronous code?
While it isn't a built-in language feature, it may be interesting to note that it's possible to implement C# style async/await for Swift, and that because of the special syntax afforded to the last closure argument of a function call, it even looks like it might be part of the language.
If anyone is interested, you can get code for this on Bitbucket. Here's a quick taster of what's possible:
let task = async { () -> () in
let fetch = async { (t: Task<NSData>) -> NSData in
let req = NSURLRequest(URL: NSURL.URLWithString("http://www.google.com"))
let queue = NSOperationQueue.mainQueue()
var data = NSData!
NSURLConnection.sendAsynchronousRequest(req,
queue:queue,
completionHandler:{ (r: NSURLResponse!, d: NSData!, error: NSError!) -> Void in
data = d
Async.wake(t)
})
Async.suspend()
return data!
}
let data = await(fetch)
let str = NSString(bytes: data.bytes, length: data.length,
encoding: NSUTF8StringEncoding)
println(str)
}
Also, if you want something like #synchronized, try this:
func synchronized(obj: AnyObject, blk:() -> ()) {
objc_sync_enter(obj)
blk()
objc_sync_exit(obj)
}
var str = "A string we can synchronise on"
synchronized(str) {
println("The string is locked here")
}
Swift's approach to asynchronous programming is the same as Objective C's: use Grand Central Dispatch. You can pass closures to gcd dispatch_ functions, just as in ObjC. However, for aesthetic reasons, you can also pass your closure (block) after the close parentheses:
dispatch_async(dispatch_get_main_queue()) {
println("async hello world")
}

If nodejs uses non blocking IO, how is fs.readFileSync implemented?

I see a lot of synchronous functions in the file system library. such as fs.readFileSync(filename, [options]).
How (and why) are these functions implemented if node has async/non-blocking IO and no sleep method - and can I use the same mechanism to implement other synchronous functions?
fs.readFileSync()
is really just a wrapper for the
fs.readSync()
function. So the question is how is fs.readSync() implemented compared to fs.read(). If you look at the implementations of these two functions they both take advantage of the bindings module. Which in this case is intialized to
var binding = process.binding('fs').
and the calls are
binding.read(fd, buffer, offset, length, position, wrapper);//async
var r = binding.read(fd, buffer, offset, length, position);//sync
Respectively. Once we're in the "binding" module, we are out in v8, node_#####.cc land. The implementation of binding('fs') can be found in the node repository code, in node_file.cc. The node engine offers overloads for the C++ calls, one taking a callback, one that does not. The node_file.cc code takes advantage of the req_wrap class. This is a wrapper for the v8 engine. In node_file.cc we see this:
#define ASYNC_CALL(func, callback, ...) \
FSReqWrap* req_wrap = new FSReqWrap(#func); \
int r = uv_fs_##func(uv_default_loop(), &req_wrap->req_, \
__VA_ARGS__, After); \
req_wrap->object_->Set(oncomplete_sym, callback); \
req_wrap->Dispatched(); \
if (r < 0) { \
uv_fs_t* req = &req_wrap->req_; \
req->result = r; \
req->path = NULL; \
req->errorno = uv_last_error(uv_default_loop()).code; \
After(req); \
} \
return scope.Close(req_wrap->object_);
#define SYNC_CALL(func, path, ...) \
fs_req_wrap req_wrap; \
int result = uv_fs_##func(uv_default_loop(), &req_wrap.req, __VA_ARGS__, NULL); \
if (result < 0) { \
int code = uv_last_error(uv_default_loop()).code; \
return ThrowException(UVException(code, #func, "", path)); \
}
Notice that the SYNC_CALL uses a different req-wrap. Here is the code for the relevant req_wrap constructor for the ASYNC method, found in req_wrap.h
ReqWrap() {
v8::HandleScope scope;
object_ = v8::Persistent<v8::Object>::New(v8::Object::New());
v8::Local<v8::Value> domain = v8::Context::GetCurrent()
->Global()
->Get(process_symbol)
->ToObject()
->Get(domain_symbol);
if (!domain->IsUndefined()) {
// fprintf(stderr, "setting domain on ReqWrap\n");
object_->Set(domain_symbol, domain);
}
ngx_queue_insert_tail(&req_wrap_queue, &req_wrap_queue_);
}
Notice that this function is creating a new v8 scope object to handle the running of this event. This is where the asynchronous portion of async stuff happens. The v8 engine launches a new javascript interpreting environment to handle this particular call separately. In short, without building/modifying your own version of node, you cannot implement your own asynchronous/synchronous versions of calls, in the same way that node does. That being said, asynchronous really only applies to I/O operations. Perhaps a description of why you think you need things to be more synchronous would be in order. In general, if you believe node doesn't support something you want to do, you just aren't embracing the callbacks mechanism to it's full potential.
That being said, you could consider using the events node module to implement your own event handlers if you need async behavior. And you can consider native extensions if there are things you desperately need to do synchronously, however, I highly recommend against this. Consider how you can work within the asynchronous event loop to get what you need to do done this way. Embrace this style of thinking, or switch to another language.
Forcing a language to handling things a way it doesn't want to handle them is an excellent way to write bad code.

Resources