Boost.Python: Grab 'self' from member function - c++

Class member functions in Python have to explicitly declare a self parameter which represents the class instance. Is there a way to get a hold of self from C++, by using Boost?
class FooBar
{
public:
void func() {
}
};
// A wrapper for the above class
struct FooBar_W
: public FooBar
{
void func(boost::python::object self) {
// Do smth with `self`
FooBar::func();
}
};
BOOST_PYTHON_WRAPPER(module)
{
class_<FooBar_W>("FooBar")
.def("func", &FooBar_W::func)
;
}
Edit: Why I want self
I'm writing an event system for my game and I want the scripter to be able to define new types of events. I need a way to distinguish between different types of events. My Python code looks something like this:
class KeyboardEvent(Event):
pass
def onKeyPress(event):
pass
# EventManager is defined in C++
em = EventManager()
# This is how I register a new callback function with the manager
# The `onKeyPress` function will now only be notified when an event
# of type `KeyboardEvent` occurs. (Notice that I passed the actual
# class object, and not an instance of it.)
em.addEventHandler(KeyboardEvent, onKeyPress)
# This is how I queue new events
# (This time I pass an instance of an event, not a type of event.)
em.queueEvent(KeyboardEvent())
The manager needs to figure out what type of event I just queued. I figured I should do something like type(event).__name__ (but in C++, not in Python). This way I can determine the type and know which functions to notify of the event. I want to get self in C++ so I can access the __name__ attribute of its type.
I could have the scripter manually edit a new field that holds the name of the type, but why? That information already exists (the __name__ attribute) so why duplicate it, but more importantly, why bother the scripter with implementation details?

It's doable. The way to do it can be found in the link below; that page documents one way (the old way) to expose pure virtual functions. The example can be adapted to other needs, though.
> http://wiki.python.org/moin/boost.python/OverridableVirtualFunctions#Pure_Virtual_Functions

it's an old question, but for those who are still looking for a reasonably simple solution:
Static function (non-member as well as member) receive a const boost::python::object& self as the first argument. So you can do the following:
class FooBar
{
public:
static void func(const boost::python::object self) {
FooBar& thisref = boost::python::extract<FooBar&>(self)();
// use self as well as thisref
}
};
};
BOOST_PYTHON_WRAPPER(module)
{
class_<FooBar>("FooBar")
.def("func", &FooBar::func)
;
}

self in python is this in C++.
You can think of the line FooBar::func(); as translating to static_cast<FooBar*>(this)->func()

Related

Creating a wrapper method in C++ at runtime - prototype known

I'm currently wrapping around an API that takes function pointers and calls them back at some point. The only issue is that the prototype for this callback function provides a pointer to the state I'm wrapping around instead of my new class. My goal is to hide the original API from the user, so I need a way to dynamically create a method that calls back a different function whose prototype is instead my new class. Here's a simplified code visualisation.
struct Old_API
{
public:
typedef int (*OldCallback)(Old_API*);
void RegisterCallback(OldCallback);
};
class New_API
{
private:
Old_API* m_WrappedState;
public:
typedef int (*NewCallback)(New_API*);
New_API() { m_WrappedState = new Old_API; }
void RegisterCallback(NewCallback func)
{
// Pseudocode, obviously won't work
// This is the actual method that would be called back from Old_API
// It acts as a buffer to call the "new" format of callbacks
int CallbackLayer(Old_API* state)
{
m_WrappedState = state;
return func(this);
}
m_WrappedState->RegisterCallback(&CallbackLayer);
}
};
// This is what it would look like in runtime
int SomeCallback(New_API*)
{
// Code
}
New_API* state;
int main()
{
state = new New_API;
state->RegisterCallback(&SomeCallback);
return 0;
}
Specifications
Must be done at runtime so passing the function pointer as a template parameter won't work.
Instances of New_API are created by the user and are nearly stateless - they simply wrap around arbitrary Old_API instances.
Old_API instances are passed to the callback function and don't map to a single New_API instance. The "CallbackLayer" method is intended to remove the need for the user to have to setup the state themselves, thus hiding Old_API's implementation.
If you're fully wrapping the interface, it makes this easy.
First New_API registers its own listener on Old_API, using whatever means Old_API offers to associate the callback with that instance of New_API (could just be a field in Old_API, or if that's not available, even something like a static unordered_map<Old_API*, New_API*>).
Then, New_API has its own system for registering listeners. (You're showing function pointers here, but that's C thinking... at worst, you should have something which takes a std::function.)
When New_API gets its notification, it simply notifies its own listener(s) in turn. There's no direct mapping between listeners: Old_API will have exactly one listener, regardless of how many listeners are on New_API.

object.Object.Monitor being prefered over own Monitor class

I am in progress of writing a render system in D2, but it is really annoying me that D prefers its own monitor class object.Object.Monitor (Which I never imported by the way) over my own Monitor class.
What's a way to prevent D from using its monitor class instead of mine? I know I could append the conventional underscore, or simply use its full name (myapp.graphics.x11.Monitor) but this class will be used an awful lot, so these fixes aren't really ideal.
module app;
class Monitor {
public Monitor returnMe() {
return this; // Error: cannot implicitly convert expression (this) of type app.Monitor to object.Object.Monitor
}
}
void main() {
Monitor monitor = new Monitor;
monitor.returnMe();
}
I think this is because inside the class Monitor, your class name doesn't quite exist yet so the compiler thinks the already existing Monitor (it is in object.d which is auto imported) is a better match.
I actually think this should be considered a compiler bug, since if the other Monitor didn't exist, this code would indeed work. edit: Actually, since Monitor is a nested class in Object, this is /not/ a compiler bug, nested names always override outer names. So it is just weird that Object base class has a nested one called Monitor. /edit
But to work around the thing for now, you can use typeof(this) inside the Monitor class instead of its name. That will disambiguate inside, and the outside code still works correctly:
module app;
class Monitor {
// changed the name only inside the class
public typeof(this) returnMe() {
return this;
}
}
void main() {
// works normally here
Monitor monitor = new Monitor;
monitor.returnMe();
}

A proper way to restrict access to an interface?

Let's say I have a class that represents a printing job: CPrintingJob. It knows nothing of the document being printed, just the job state - whether the job was queued, rejected, carried on etc.
The idea is an object of this class is instantiated whenever some printing needs to be done, then passed to the printing module along with other data, then the job's creator checks its state to see how printing is going.
Suppose CPrintingJob inherits two interfaces:
class IPrintingJob // this one is to check the job state
{
virtual TState GetState() const = 0;
// ... some other state-inquiring methods
class ICallback // job's owner is notified of state changes via this one
{
virtual void OnStateChange( const IPrintingJob& Job ) = 0;
};
};
and
class IPrintingJobControl // this one is for printing module to update the state
{
virtual void SetState( const TState& NewState ) = 0;
// ... some other state-changing methods
};
Problem is, the class that creates a CPrintingJob object shouldn't have access to the IPrintingJobControl, but the printing module CPrintingJob is being passed to must be able to change its state and, therefore, have access to that interface.
I suppose this is exactly the case where friends should be used but I have always avoided them as an inherently flawed mechanic and consequently have no idea of how to use them properly.
So, how do I do it properly?
Use a factory and have the factory return an instance of IPrintingJob (best wrapped inside a smart_ptr). e.g.:
struct PrintingFactory {
static auto create() -> std::unique_ptr<IPrintingJob> {
return std::unique_ptr<IPrintingJob>(new CPrintingJob());//as there is currently no std::make_unique..
}
}
Once you have to use the JobControl you can simply cast the pointer via std::dynamic_pointer_cast.
After some deliberation I've decided that:
This whole thing is definitely more trouble than it's worth;
(A slightly modified) version of MFH's answer above is the only, hence the best, way to go.
Thanks everyone for the input, it certainly has been enlightening.

OO Design -- where to put non-member functions

I have a class with a complex construction process with many parameters. Multiple clients share objects of this class, and the union of these clients parameters are used to instantiate the class. Therefore I have a factory class that stores these requirements, checks consistency of the various clients' requests, and instantiates the class.
Additionally, there are a common set of use models (or sets of parameters) which multiple clients use for multiple factories.
For instance, consider an example. (Note that the actual code is C++, but my experience is in Python so I'll pseudo-code in Python. Yes, I know that this example wouldn't actually work as-is.)
class Classroom:
def __init__(self, room_size=None, n_desks=None, n_boards=None,
n_books=None, has_globe=False, ... ):
...
class ClassroomFactory:
def __init__(self):
self._requirements = dict()
def addRequirement(self, name, value):
if name.startswith("n_"):
self._requirements[name] = max(value, self._requirements.get(name, 0))
...
def createClassroom(self):
return Classroom(**self._requirements)
# instantiate the factory
factory = ClassroomFactory()
# "client 1" is a geography teaacher
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
factory.addRequirement("has_globe", True)
# "client 2" is a math teacher
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
# "client 3" is a after-school day-care
factory.addRequirement("room_size", (20,20))
factory.addRequirement("has_carpet", True)
room = factory.createClassroom()
The common use model is as a teacher, we need 10 desks and a board. I think this is best served by a non-member function/decorator, something like:
def makeTeacherRoom(factory):
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
return factory
This seems like a great example of the "prefer non-member/non-friend to member" paradigm.
The thing that I'm struggling with is, within the framework of a much bigger OO code, where should these types of non-member functions/decorators live, both in terms of namespace and in terms of actual file?
Should they live in the factory's file/namespace? They are closely related to the factory, but they're limitations on the general factory, and need not be used to use the factory.
Should they live in the client's file/namespace? The client understands these use models, but this would limit re-use amongst multiple clients.
Should they live with a common base class of the clients (for instance, one could imagine a "teacher" class/namespace which would also provide the non-member function makeTeacherRoom(), which would be inherited by MathTeacher and GeographyTeacher.
Should they live somewhere else completely, in a "utils" file? And if so in which namespace?
This is primarily a personal decision. Most of your options have no technical negative effects. For example:
They could, because of locality of use, but it's not necessary.
They could, because of locality of data, but again...
They could, although this one does seem like it could make things a bit messier. Making utility classes, you may have to end up inheriting them, or making parts virtual to override later, which will get ugly pretty quick.
This is my personal favorite, or a variant of this.
I typically make a relevantly-named util file (or class with static methods) and put it in the same namespace as the classes it utilates (the more helpful version of mutilate). For a Education::Teacher class, you could have a Education::TeacherUtils file or class containing the functions that operate on Teacher. This keeps a pretty obvious naming tie-in, but also puts the util functions in their own area, so they can be included from whatever needs them (in the Teacher.cpp or similar would prevent that). In the case of a class, you can make the util and base classes friends, which is occasionally helpful (but something to use rarely, as it may be a smell).
I've seen a naming variation, Education::Utils::Teacher, but that's somewhat harder to translate to files (unless you put things into a utils dir) and can also cause name resolution oddness (in some contexts, the compiler may try to use Education::Utils::Teacher instead of Education::Teacher when you didn't mean to). Because of this, I prefer to keep utils as a suffix.
You may want to handle non-member functions in a singleton class for your application. A factory maybe executed from the program, or another object.
C++ supports global functions (non member functions), but, using a single object for the application, "does the trick".
Additionally, since the "Classroom" object may be instantiated with many optional parameters, you may want to assign it, after calling the constructor ( "init" in python ).
// filename: "classrooms.cpp"
class ClassroomClass
{
protected:
int _Room_Size;
int _N_Desks;
int _N_Boards;
int _N_Books;
bool _Has_Globe;
public:
// constructor without parameters,
// but, can be declared with them
ClassroomClass()
{
_Room_Size = 0;
_N_Desks = 0;
_N_Boards = 0;
_N_Books = 0;
_Has_Globe = false;
} // ClassroomClass()
public int get_Room_Size()
{
return _Room_Size;
}
public void set_Room_Size(int Value)
{
_Room_Size = Value;
}
// other "getters" & "setters" functions
// ...
} // class ClassroomClass
class ClassroomFactoryClass
{
public:
void addRequirement(char[] AKey, char[] AValue);
} // class ClassroomFactoryClass
class MyProgramClass
{
public:
ClassroomFactoryClass Factory;
public:
void makeTeacherRoom();
void doSomething();
} // class MyProgramClass
void MyProgramClass::addRequirement(char[] AKey, char[] AValue)
{
...
} // void MyProgramClass::addRequirement(...)
void MyProgramClass::makeTeacherRoom()
{
Factory.addRequirement("n_desks", "10")
Factory.addRequirement("n_boards", "1")
} // void MyProgramClass::makeTeacherRoom(...)
void MyProgramClass::doSomething()
{
...
} // void MyProgramClass::doSomething(...)
int main(char[][] args)
{
MyProgramClass MyProgram = new MyProgramClass();
MyProgram->doSomething();
delete MyProgram();
return 0;
} // main(...)
Cheers
Personally I would make them static members of the class.
class File
{
public:
static bool load( File & file, std::string const & fileName );
private:
std::vector< char > data;
};
int main( void )
{
std::string fileName = "foo.txt";
File myFile;
File::load( myFile, fileName );
}
With static methods they have access to the private data of the class while not belonging to a specific instance of the class. It also means the methods aren't separated from the data they act on, as would be the case if you put them in a utility header somewhere.

Dynamic creating of typedef

I'm creating event system. It's based under boost::signals. To make the work easier I'm using typedef for the function signatures.
Everything is okey until I need creating of some new event trought event's system method. I have to create the typedef dynamically on given type to the template function. The problem is the name of typedef.
Some pseudocode I would have:
template<typename EventType>
void create(const string &signalName)
{
typedef EventType signalName;
// ...
}
Is it possible to make such typedef (their names) with some passed string or data or something else? I don't want to make user care about of this.
UPD: So, I have some typedefs list of function signatures - events. I have some templated function for connecting slots, for example. I don't want to force user to input signature by his hands again every time (user is programmer which will use the event system). So I just use my typedefs from special namespace into template argument.
typedefs only matter during compilation. As far as I know it's just an alias for a type.
Template parameters are, by definition, compile time entities. You can not dynamically create template classes on the fly during program execution as far as I am aware.
In this case, I wouldn't go for typedef's. If you want to have several types of events and create them dynamically, you can use a simple class containing the information about the event type. When you have an event, you link it to the event type created before.
Something like this:
class EventType
{
private:
string type;
EventType(string type);
};
class Event
{
private:
string event_name;
EventType *event_type;
Event(string event_name, EventType event_type);
};
...
void create(const string &signalName)
{
EventType *event_type = new EventType("type_x");
Event *event = new Event("event_x", event_type);
}