Calling java parent method from Clojure - clojure

Say I have a java library with the following pseudo code :
abstract class B {
public void method2(String param2) {...}
}
class A extends B {
public void method1(String param1) {...}
}
I want to use this from Clojure.
I have an instance of A, and I want to invoke method2 without going through Reflection methods.
What's the quickest way ?

If you have an instance of A you can just call method2 using normal interop:
(.method2 (A.) "param")

Related

Writing C++ tests with "faking" some methods with an alternative implementation

I'm writing tests in C++ using googleTest and want to improve them.
I try to describe what I have and what I want to achieve:
I have a class A that has an instance of class B as a member like this:
class ClassA
{
public:
//Some functions
protected:
ClassB m_b;
};
class ClassB
{
void Init(const string &sArgument);
};
In my test I create an instance of ClassA and call a function of it. In this function the function Init() of m_b will be called.
Because Init() of ClassB makes something that I don't want to have in my test I want to call an alternate implementation. My first intention was to create an interface with the function Init() that is implemented by ClassB and by a new class that I create only for the test. Unfortunately to do this I have to create a pointer of the interface and to give it to ClassA.
__interface IB
{
void Init(const string &sArgument);
};
class ClassB : public IB
{
void Init(const string &sArgument) override;
};
class ClassA
{
public:
ClassA(IB* b) : m_b(b){}
//Some functions
protected:
*IB m_b;
};
For my test I create a new class:
class ClassBForTest : public IB
{
void Init(const string &sArgument) override;
};
This is not a good solution so I tried to find another way. What I actually found is the library Isolator++ by Typemock which works quite good. I can say that for all future instances of ClassB the method Init should be replaced with another one. And the best is that I don't have to make any changes in my ClassA. I just have to create a new one:
class ClassBForTest
{
void ISOLATOR_TESTABLE Init(const string &sArgument){}
};
In my test I use this:
ClassBForTest c;
ClassB* b = FAKE_ALL<ClassB>();
WHEN_CALLED(b->Init(ANY_VAL(string))).DoMemberFunctionInstead(&c, Init);
Unfortunately this library is not for free when I want to use it on a build server. So I'm searching for an alternative. As we used gMock in our other tests I tried to realize this with gmock but it didn't work yet. I know that this is not a good statement but I don't want code from you. I only want to know if this is possible with gMock (saying that an alternate implementation should be used without having the instance of ClassB at this point).
Alternatively I ask you for other free libraries I can use.
Thanks a lot in advance,
Michaela

C++ Passing member function reference from a class instance to another class instance

I'm very new to C++ and I'm struggling on a project where I need to transmit a reference to a callback method between to different class instances. I know that this subject is a pretty common issue for C++ beginners. I understand that member function pointers are different from the "standard" function ones, but I cannot find any post that adresses my specific problem (but may be it is because, given my lack of experience with C++ I don't understand the provided answers).
The system I try to develop is based on :
A ControllerManager class (which is a Singleton)
A Controller base class
Some specific Controller classes (FanController, LighController, etc) which inherits from the Controller class
What I would like to do is from let say a FanController instance to call an addCallback method of the ControllerManager class. This method would take as a parameter a pointer to any public method of the FanController so that the ControllerManager could made a callback to this method later (I must specify that the ControllerManager include the definition of the Controller class but doesn't know anything about the FanController class)
So far I didn't found any working solution, the only thing I managed to get is a very poor workaround (for simplicity, only relevant methods are indicated) :
class Controller {
public:
virtual void callback();
};
class FanController:Controller {
public:
virtual void callback();
};
class ControllerManager
{
private:
static ControllerManager *_instance;
Controller *_controller;
public:
void addCallback(Controller * controller)
{
_controller = controller;
}
static void periodicCallback()
{
_instance->_controller->callback();
}
};
At runtime the FanController instance provides a reference of herself to the ControllerManager singleton :
ControllerManager::getInstance()->addController(this);
and the ControllerManager can make a call to the callback method of the FanController instance:
_instance->_controller->callback();
This workaround is very limited since it allows only calls to methods declared by the parent Controller class.
What I would to implement is a system that allows the specifics controllers to provide references of their member methods (which doesn't exist in the Controller class) to the ControllerManager so that it can make calls to those methods.
If someone can help me I thanks him/her in advance.
The modern way of tackling this is to squirrel away the method's binding in a lambda.
#include <functional>
#include <vector>
class Controller {
std::vector<std::function<void()>> callbacks_;
public:
void addCallback(std::function<void()> cb) {
callbacks_.push_back(std::move(cb));
}
void periodicCallback() {
for(const auto& cb : callbacks_) {
cb();
}
}
};
class Fan {
public:
void whatever() {}
void register_in_controller(Controller* tgt) {
tgt->addCallback([this]{whatever();});
}
};

Static create methods in boost python

I am trying to create an object using boost python. The class definition (pseudocode):
class Awrap : public A, public boost::python::wrapper<A> {
static std::shared_ptr<A > Create(...) { ... } // inherited from A
virtual double foo(...) override { // overrides pure virtual function in A
return this->get_override("foo")(...);
}
};
BOOST_PYTHON_MODULE() {
using namespace boost::python
class_<Awrap,std::shared_ptr<Awrap>, boost::noncopyable>("A",boost::python::no_init)
.def("Create",&A::Create).staticmethod("Create")
.def("foo",pure_virtual(&Awrap::foo));
boost::python::register_ptr_to_python<std::shared_ptr<A> >();
}
The problem is that when I implement the child in python and call the static create method it creates a pointer to Awrap (not the child). So it cannot find the python-implemented version of "foo". If I implement foo in the Awrap class instead of the python child it works fine, but I don't want to do this!
Any suggestions?
Thanks!
You need to expose both Awrap::foo and A::foo to boost python. See example in:
http://www.boost.org/doc/libs/1_54_0/libs/python/doc/tutorial/doc/html/python/exposing.html

Wrapping C# C++

I would like to wrap a native library with C++/CLI. It's work with primitive type. But in the following case, it's more complicated :
interface ISampleInterface
{
void SampleMethod();
}
public ref class NativeClassWrapper {
NativeClass* m_nativeClass;
public:
NativeClassWrapper() { m_nativeClass = new NativeClass(); }
~NativeClassWrapper() { delete m_nativeClass; }
void Method(ISampleInterface ^i) {
???
m_nativeClass->Method(i);
}
};
How to wrap this ? Because the native code C++ doesn't know the ISampleInterface type... (Same question with a virtual class)
Thanks you.
There are some mistakes in the code snippet. Let's start with a clean example, declaring the native class first:
#pragma unmanaged
class INativeInterface {
public:
virtual void SampleMethod() = 0;
};
class NativeClass {
public:
void Method(INativeInterface* arg);
};
And the managed interface:
#pragma managed
public interface class IManagedInterface
{
void SampleMethod();
};
So what you need is a native wrapper class that derives from INativeInterface so that you can pass an instance of it to NativeClass::Method(). All that this wrapper has to do is simply delegate the call to the corresponding managed interface method. Usually a simple one-liner unless argument types need to be converted. Like this:
#pragma managed
#include <msclr\gcroot.h>
class NativeInterfaceWrapper : public INativeInterface {
msclr::gcroot<IManagedInterface^> itf;
public:
NativeInterfaceWrapper(IManagedInterface^ arg) : itf(arg) {};
virtual void SampleMethod() {
itf->SampleMethod();
}
};
Now your method implementation becomes easy:
void Method(IManagedInterface^ i) {
NativeInterfaceWrapper wrap(i);
m_nativeClass->Method(&wrap);
}
If your native class needs to callback into .NET code, you need to use the gcroot template. Wuth this you can store the managed object in an unmanaged class. In this unmanaged class you can then use a native "callback" and then use the member stored in `gcroot´ to callback into managed code (ISampleInterface).
See also:
How to: Declare Handles in Native Types
How to: Hold Object Reference in Native Function
Best Practices for Writing Efficient and Reliable Code with C++/CLI

C++ dynamic type construction and detection

There was an interesting problem in C++, but it was more about architecture.
There are many (10, 20, 40, etc) classes describing some characteristics (mix-in classes), for example:
struct Base { virtual ~Base() {} };
struct A : virtual public Base { int size; };
struct B : virtual public Base { float x, y; };
struct C : virtual public Base { bool some_bool_state; };
struct D : virtual public Base { string str; }
// ....
The primary module declares and exports a function (for simplicity just function declarations without classes):
// .h file
void operate(Base *pBase);
// .cpp file
void operate(Base *pBase)
{
// ....
}
Any other module can have code like this:
#include "mixing.h"
#include "primary.h"
class obj1_t : public A, public C, public D {};
class obj2_t : public B, public D {};
// ...
void Pass()
{
obj1_t obj1;
obj2_t obj2;
operate(&obj1);
operate(&obj2);
}
The question is how do you know what the real type of a given object in operate() is without using dynamic_cast and any type information in classes (constants, etc)? The operate() function is used with a big array of objects in small time periods and dynamic_cast is too slow for it and I don't want to include constants (enum obj_type { ... }) because this is not the OOP-way.
// module operate.cpp
void some_operate(Base *pBase)
{
processA(pBase);
processB(pBase);
}
void processA(A *pA)
{
}
void processB(B *pB)
{
}
I cannot directly pass a pBase to these functions. And it's impossible to have all possible combinations of classes, because I can add new classes just by including new header files.
One solution that came to mind, in the editor I can use a composite container:
struct CompositeObject
{
vector<Base *pBase> parts;
};
But the editor does not need time optimization and can use dynamic_cast for parts to determine the exact type. In operate() I cannot use this solution.
So, is it possible to avoid using a dynamic_cast and type information to solve this problem? Or maybe I should use another architecture?
The real problem here is about what you are trying to achieve.
Do you want something like:
void operate(A-B& ) { operateA(); operateB(); }
// OR
void operate(A-B& ) { operateAB(); }
That is, do you want to apply an operation on each subcomponent (independently), or do you wish to be able to apply operations depending on the combination of components (much harder).
I'll take the first approach here.
1. Virtual ?
class Base { public: virtual void operate() = 0; };
class A: virtual public Base { public virtual void operate() = 0; };
void A::operate() { ++size; } // yes, it's possible to define a pure virtual
class obj1_t: public A, public B
{
public:
virtual void operate() { A::operate(); B::operate(); }
};
Some more work, for sure. Notably I don't like the repetition much. But that's one call to the _vtable, so it should be one of the fastest solution!
2. Composite Pattern
That would probably be the more natural thing here.
Note that you can perfectly use a template version of the pattern in C++!
template <class T1, class T2, class T3>
class BaseT: public Base, private T1, private T2, private T3
{
public:
void operate() { T1::operate(); T2::operate(); T3::operate(); }
};
class obj1_t: public BaseT<A,B,C> {};
Advantages:
no more need to repeat yourself! write operate once and for all (baring variadic...)
only 1 virtual call, no more virtual inheritance, so even more efficient that before
A, B and C can be of arbitrary type, they should not inherit from Base at all
edit the operate method of A, B and C may be inlined now that it's not virtual
Disadvantage:
Some more work on the framework if you don't have access to variadic templates yet, but it's feasible within a couple dozen of lines.
First thing that comes to mind is asking what you really want to achieve... but then again the second thought is that you can use the visitor pattern. Runtime type information will implicitly be used to determine at what point in the hierarchy is the final overrider of the accept method, but you will not explicitly use that information (your code will not show any dynamic_cast, type_info, constants...)
Then again, my first thought comes back... since you are asking about the appropriateness of the architecture, what is it that you really want to achieve? --without knowledge of the problem you will only find generic answers as this one.
The usual object oriented way would be to have (pure) virtual functions in the base class that are called in operate() and that get overridden in the derived classes to execute code specific to that derived class.
Your problem is that you want to decide what to do based on more than one object's type. Virtual functions do this for one object (the one left of the . or ->) only. Doing so for more than one object is called multiple dispatch (for two objects it's also called double dispatch), and in C++ there's no built-in feature to deal with this.
Look at double dispatch, especially as done in the visitor pattern.