I am going through the boost::asio examples. I am looking at
Example 4
What is confusing is that, the WaitHandler in this example has the signature
void print (this)
But the async_wait call expects a handler whose
function signature of the handler must be:
void handler(
const boost::system::error_code& error // Result of operation.
);
Source: Boost documentation
Since the parameter type is part of a function's signature, why in the example above, async_wait accepts a handler whose parameter is not of type boost::system::error_code?
THanks.
As you correctly observe, the async_wait method accepts a handler function which takes one parameter (const boost::system::error_code&). But in the Timer.4 example, the call to async_wait is passed via boost bind as follows:
timer_.async_wait(boost::bind(&printer::print, this));
The boost::bind returns a function object which refers to method print for class printer for the object referenced by this. This function object is called by the async_wait method with the error parameter (since that is the signature it expects). But the error parameter is silently ignored because it is not referenced by the bind.
The official boost::bind documentation provides more details on boost::bind. See also the article How the Boost Bind Library Can Improve Your C++ Programs (there are probably many more articles available but I found this one very useful).
You specify in the call to async_wait what parameters your callback function takes, using placeholders. Check the sentence just above the async_wait call on the page you linked to:
You will note that the boost::asio::placeholders::error placeholder is
not specified here, as the print member function does not accept an
error object as a parameter.
Search for "placeholder" in this example and you'll see how to do it.
Related
I'm dealing with the following thunk in Ghidra:
Now when I double-click the thunked function, Ghidra takes me to the real function, and I can see that it expects 2 parameters ("param_1" and "param_2").
Why is it allowed to call it with a single parameter ("&LAB_30007a18") only?
Thank you!
You showed the definition for the thunked function, but not the thunk. The thunk's signature may only include 1 param instead of 2. If so, fix that. Otherwise, the Decompiler may be confused by something earlier in the calling function (e.g., the 2nd param passed to the thunk is the return value from a previous call to a function that is currently defined as having a void return type).
The Decompiler can produce odd-looking results when functions are defined with incorrect parameters or return types.
I have a custom Dialog class (derived from wxDialog). I want to add a setter so you can set a call back function MyDialog::m_f with some function of type std::function<bool(wxString&)>.
Later, the dialog will call this function.
I want to be able to pass in a lambda function (otherwise I could solve my problem with ordinary function pointers).
It must also be possible to call this setter multiple times, the last set value for m_f should be valid, thus erasing any previous set values (the value being a new function).
But, if I declare the member m_f, does it have to be initialized in the initializer list in the constructor?
For my use case that would not really work. I have to be able to set MyDialog::m_f after the dialog has been constructed (but before ShowModal is called).
Should my member m_f be a (unique) pointer to a std::function<bool(wxString&)>, so it can be set to nullptr in MyDialog::MyDialog?
My basic problem is I do not fully understand std::function. How can you make a variable of some std::function<...> type and assign a value (concrete function) to it later? What does it mean to have a variable like described which is uninitialized? How can I test whether it is (un)assigned? Is it at all possible to delay this assignment, that is: have a separate declaration and later initialization, or should a variable of std::function<...> be initialized immediately (like a const or reference)?
Thanks for any help.
BTW, the language is C++11 and we can't upgrade due to restrictions at work.
How can you make a variable of some std::function<...> type and assign a value (concrete function) to it later?
std::function has a default constructor that results in an "empty" instance. In your case, just declare the data member std::function<...> m_f and don't explicitly initialize it.
What does it mean to have a variable like described which is uninitialized?
That depends on the type of the variable. In the std::function, it's simply unusable. If you try to inoke an empty std::function, and exception will be thrown.
How can I test whether it is (un)assigned?
std::function has an explicit conversion operator to bool. It evaluates to true when the object is non-empty, i.e.
if (m_f)
m_f(/* parameters... */);
else
; // do nothing, not set yet
How can you make a variable of some std::function<...> type and assign a value (concrete function) to it later?
If you want to later assign lambda expression to the function object through a setter, you can turn this member function into a template, e.g.
template<class Fct>
void setCallback(Fct&& f)
{
m_f = std::forward<Fct>(f);
}
Another option is to pass a std::function with the desired signature to a non-template member function.
Informs the provider that a directory enumeration is starting
`
PRJ_START_DIRECTORY_ENUMERATION_CB PrjStartDirectoryEnumerationCb;
HRESULT PrjStartDirectoryEnumerationCb(
const PRJ_CALLBACK_DATA *callbackData,
const GUID *enumerationId
)
{...}
`
I am confused how to use this function.
You're looking at a callback (a generic programming concept, not specific to Win32), which is usually a reference to a function that you have to write yourself. In order to have the C/C++ compiler check that you've defined your callback function correctly, and to simplify usage of such callbacks, a typedef is often used. The Win32 API often uses all caps to define types of callbacks. In this case, PRJ_START_DIRECTORY_ENUMERATION_CB is the type of the function pointer (a pointer to the callback function that you have to write), and it is defined in projectedfslib.h as:
typedef
_Function_class_(PRJ_START_DIRECTORY_ENUMERATION_CB)
HRESULT
(CALLBACK PRJ_START_DIRECTORY_ENUMERATION_CB)(
_In_ const PRJ_CALLBACK_DATA* callbackData,
_In_ const GUID* enumerationId
);
This definition has a lot of excess stuff in it that helps the Microsoft toolset validate various things related to the usage of this type of function pointer. When writing your own function that works for this type of callback, you don't necessarily have to repeat a lot of the things that are used in the typedef. The MSDN documentation for callbacks often shows an example of how you would write the method signature for your callback, and that example is usually simplified to strip off the excess stuff that the toolset needs, leaving the stuff the developer needs to define when writing their callback.
In this case, the example function is called PrjStartDirectoryEnumerationCb, but there is no function defined with that name. It's up to you to define a function that looks like what you see on MSDN. It doesn't have to have the same name -- you can name it whatever you like, and then you use your function's name anywhere the callback is needed.
HRESULT MyCallback(const PRJ_CALLBACK_DATA *callbackData, const GUID* enumerationId)
{
// implement your callback here
}
Boost::bind documentation states:
By default, bind makes a copy of the provided function object. boost::ref and boost::cref can be used to make it store a reference to the function object, rather than a copy.
I am seeing excessive news and deletes in my code when I use boost::bind with a pointer to a member function. The documentation is unclear to me whether boost::bind(&classname::functionname,...) makes a copy of the function.
Or maybe the question makes no sense and as it is converting a member function into a function object it obviously has to new the function object.
So my question is there a way I can bind to a member function and avoid the new and delete?
According to my experiments (boost 1.49), boost::bind does not use dynamic memory for its own implementation. With this code
#include <boost/bind.hpp>
int f(int a , int b) {
return a>b ? a+b : a-b;
}
int main()
{
auto a = boost::bind(f, _1, 2);
return a(0);
}
I tried breaking on operator new variants in gdb and it didn't fire. So I suspect your problem is actually that boost::bind is making copies of either the bound arguments (compare the output of these two snippets) or the call arguments. Search for something among these that could allocate memory while copying, and try to get rid of it.
If you're using a C++11 compiler, you can get away with boost::bind completely and use a lambda function instead. The example would be transformed to
auto a = [&](int a1) { return f(a1, 2); }
That would only copy if you'd capture objects by value.
EDIT: With the code you posted, try changing the line in question to
TConstIterator pIt = std::find_if(rtContainer.begin(), rtContainer.end(),
boost::bind(&TValueType::bSameSocket, boost::cref(rtData), _1));
^^^^^^^^^^^
That should make it better; report if it doesn't.
What gets copied is the pointer to that method, so no new/delete involved. What bind returns is a function object that gets created and destroyed at some point, but again no dynamic memory allocation.
As far as I can tell if you use boost::bind in code such as to create a function object to act as the predicate in a find_if the function object is newed and deleted and this is what was causing my code to run slowly.
My question was: is there a way I can bind to a member function and avoid the new and delete?
I worked around the boost::bind by iterating through the list myself calling a member function through a member function pointer.
The type of the member pointer function is derived from template parameters for the list and its stored data types, but the same technique works whether the types are templated or not.
This solution reduced the user perception of response for a particular action from 5 minutes to effectively immediately.
i'm faced with implementing an IDispatch interface. There are four methods, and fortunately 3 of them are easy:
function TIEEventsSink.GetTypeInfoCount(...): HResult;
{
Result := E_NOTIMPL;
}
function TIEEventsSink.GetTypeInfo(...): HResult;
{
Result := E_NOTIMPL;
}
function TIEEventsSink.GetIDsOfNames(...): HResult;
{
Result := E_NOTIMPL;
}
It's the last method, Invoke that is difficult. Here i am faced with having to actually case the DispID, and call my appropriate method; unmarhsalling parameters from a variant array.
function Invoke(
dispIdMember: DISPID;
riid: REFIID;
lcid: LCID;
wFlags: WORD;
var pDispParams: DISPPARAMS;
var pVarResult: VARIANT;
var pExcepInfo: EXCEPINFO;
var puArgErr: DWORD
): HRESULT;
Not wanting to have to write all the tedious boilerplate code, that i'm sure will have bugs, i went googling - rather than doing any work.
i found this snippit on the MSDN Documentation of IDispatch.Invoke:
Generally, you should not implement Invoke directly.
Excellent! i didn't want to implement it anyway! Continuing reading:
Instead, use the dispatch interface to create functions CreateStdDispatch and DispInvoke. For details, refer to CreateStdDispatch, DispInvoke, Creating the IDispatch Interface and Exposing ActiveX Objects.
The Creating the IDispatch Interface link says:
You can implement IDispatch by any of the following means:
[snip]
Calling the CreateStdDispatch function. This approach is the simplest, but it does not provide for rich error handling or multiple national languages.
[snip]
Excellent, CreateStdDispatch it is:
Creates a standard implementation of the IDispatch interface through a single function call. This simplifies exposing objects through Automation.
HRESULT CreateStdDispatch(
IUnknown FAR* punkOuter,
void FAR* pvThis,
ITypeInfo FAR* ptinfo,
IUnknown FAR* FAR* ppunkStdDisp
);
i was going to call it as:
CreateStdDispatch(
myUnk, //Pointer to the object's IUnknown implementation.
anotherObject, //Pointer to the object to expose.
nil //Pointer to the type information that describes the exposed object (i has no type info)
dispInterface //the IUnknown of the object that implements IDispatch for me
);
What i cannot figure out is how the Windows API implemention of CreateStdDispatch knows what methods to call on my object - especially since CreateStdDispatch doesn't know what object-oriented language i'm using, or its calling conventions.
How will CreateStdDispatch know
what method to call for a given dispid?
the calling convention of my language?
how to handle exceptions from the language that my object oriented object is written in?
Note: i have no choice but to implement a dispinterface; i didn't define the interface. i wish it was a simple early bound IUnknown, but it tisn't.
Doesn't the ITypeInfo parameter passed into CreateStdDispatch expose all of the method information?
So you'd create type info first calling CreateDispTypeInfo and pass that through to CreateStdDispatch which can then use the type information to work out which method to call since CreateDispTypeInfo requires INTERFACEDATA which contains all this information
I could be way wrong since I don't have time to look into it but that would make sense to me.
I'll investigate this later and update the answer.
The short answer to your question is: neither CreateStdDispatch() nor the IDispatch implementation it creates knows anything at all about the methods to be called.
The object that you get back simply stores the parameters that you passed to CreateStdDispatch(), and for all IDispatch methods it only turns around and makes the corresponding calls on the ITypeInfo that you gave it. That is all.
If you pass nil for ptinfo as shown in your code then you only get E_INVALIDARG, since the implementing object cannot do anything at all without an ITypeInfo to which to delegate all the work.
If you inspect the code for CStdDisp in oleaut32.dll then you will find that it calls API functions like DispInvoke() (which also live in that DLL) instead of invoking the ITypeInfo methods directly, but these functions are all simple wrappers for calls to the ITypeInfo methods, without any further functionality.
In case anyone wonders: neither CreateStdDispatch() nor CStdDisp performs any additional magic; all they do is give you an IDispatch that does whatever the ITypeInfo that you passed in can do. Think of it as a kind of an adapter that allows you to plug an ITypeInfo into an IDispatch socket.
It is true that TAutoIntfObject.Create() needs a type library. However, all that the constructor does is call GetTypeInfoOfGuid() on it in order to get a type info pointer, to which the object then delegates most of the work related to dispatch things.
Borland in their wisdom made the member variable for the type info pointer private, which means that you really need to hand the constructor some type library or other that contains the interface in question, instead of simply writing another constructor or overriding some virtual function. On the other hand it shouldn't be too hard to load the type library via the registry or to dump parts of it to a TLB file. Inspecting a TLB with OleView gives you actual compilable IDL which is often also Borland-compilable RIDL.
CreateStdDispatch() does not know anything about exceptions either. The catching of exceptions thrown from COM methods and their conversion to HRESULT and/or IErrorInfo is compiler magic induced by Delphi's safecall keyword on the implementing method.
The same goes for the translation of HRESULTs to exceptions when calling COM methods specified as safecall in their interface declarations. The compiler simply inserts a call to #CheckAutoResult after every invocation of a safecall method; this function checks the HRESULT and throws EOleSysError if appropriate.
Simply switch the Delphi debugger to disassembly ('CPU view') to inspect all the magic that the compiler does for you!