I am using a C library called BFciLib.h which has only definitions of methods that look
like this one:
tCIRC CiVFGopen(
tCIU32 devNdx, //!< from CiSysVFGinfo()
tCIU32 modeFlags, //!< access mode flags
tCIp *cip //!< access token
);
This method (and others) is called from the methods of a class that i implemented called FGrabber, something like this:
EXIT_ON_ERROR(CiVFGopen(deviceIndex, tCIboardOpenEnums::kCIBO_exclusiveWrAccess, &interface));
I have mocked CiVFGopen method to do what i want it to do (created a C wrapper and calling my implemented behavior) but i have no idea how to link it in my FGrabber class.
tCIRC CiVFGopen(tCIU32 devNdx, tCIU32 modeFlags, tCIp *interface)
{
std::cout<<"entered the mock method";
return tCIerrorCode::kCIEnoErr;
}
Because of this, i am getting an error: multiple definition of CiVFGopen
I am not allowed to edit FGrabber, it has to stay with its production form, and just find a way to link my mock method to be used instead of the original one.
I have found namespaces, but i do not think this is what i need, since it will require me to modify FGrabber class is it not?
I didn't understand exactly what you want to do, but the error exists probably because you don't use the inline on the function definitions.
Try:
inline tCIRC CiVFGopen(
tCIU32 devNdx, //!< from CiSysVFGinfo()
tCIU32 modeFlags, //!< access mode flags
tCIp *cip //!< access token
);
Related
I am creating a V8 wrapper to my C++ object by using v8::ObjectTemplate. But on the step of generation this template I don't have full type info about C++ object and as result on JS runtime I have JS object with incomplete list of functions and properties.
And now if user try call a function that I not describe in ObjectTemplate, V8 just throw an exception in script.
Is there way to set callback which will invoke before an exception will throw?
This callback should make a deep search of user called function and return execution result it successful found.
//c++
class A{
public:
static int f1(){return 1;}
static int f2(){return 2;}
};
void create_v8_template(){
v8::Local<v8::ObjectTemplate> template_base = v8::ObjectTemplate::New(isolate);
obj_template->Set(v8pp::to_v8(isolate, "f1"), v8::FunctionTemplate::New(isolate, A::f1));
}
//js
a.f1(); //success
a.f2();// throw exception: "a.f2 is not a function". I need that V8 will invoke my callback there instead the exception
There is no way to automatically map JavaScript method/property lookups to C++ method/property names. One reason for this is that regular Release-mode C++ binaries don't even contain those names any more. This is usually not a problem/limitation because C++ classes are statically known at compile time, they can't be extended dynamically later.
I can think of two cases where you don't have statically known classes, and corresponding approaches to solve them:
If you know the superset of possibly existing functions, you can register them all on the ObjectTemplate, and then when a method is called, check whether it actually exists, and otherwise return undefined (or whatever) from your C++ callback. This might work well e.g. if you have a set of subclasses, where any one of them can get instantiated to fill the role of the C++ object.
If you want to expose an arbitrary key/value structure (e.g. a database, or something that was parsed from JSON, etc) as an object to JavaScript, where you truly have no idea at compile time what might be valid keys, then you can use V8's interceptors API. That essentially boils down to telling V8 "whenever any property is requested from this object, first ask this callback whether that property exists". Of course in the interceptor callback, you then need a way to find out whether the property (f2 in your example) exists.
I was reading the documentation of Qt 5.5 about Q_PROPERTY macro, but I can't understand it well enought.
I understand that you can use in this macro with the keyword MEMBER or the accessors READ/WRITE instead. If you use keyword MEMBER you don't have to write the accessors, because you can access to your private data member (the property) with the use of setProperty() and Property(), like a set and get.
The point is: is there any difference between using MEMBER and using READ/WRITE?
when should you use one and when the other way?
For if necessary:
Example of using MEMBER:
Q_PROPERTY(QString text MEMBER m_text NOTIFY textChanged)
Example of using READ/WRITE:
Q_PROPERTY(int propX READ getX WRITE setX)
By reading carefully the documentation, it seems to me that there are slightly, important differences.
First of all:
A MEMBER variable association is required if no READ accessor function is specified. This makes the given member variable readable and writable without the need of creating READ and WRITE accessor functions.
That means that you can either use MEMBER and rely on auto generated, trivial accessor functions or define for yourself those functions if they happen to be more complex than a defaulted one.
In other terms, if your accessor functions are all the way the same, as an example:
int propName() const { return prop; }
Thus, MEMBER is fine. It does not if you have something like:
int propName() const { return superComplexMathUsedToComputeProp(); }
Also, note that:
The READ, WRITE, and RESET functions can be inherited. They can also be virtual.
If you are dealing with a hierarchy, maybe you want them to be inherited, so maybe to go with READ and WRITE would be better.
Which is the best and what to use depends on the specific problem.
The MEMBER creates just ReadProperty and WriteProperty features in qt meta object system(see the generated moc file). This is useful for interfacing with QMLs. In order to use property in c++, the getters and setters has to be implemented as well.
So:
MEMBER -> just for QMLs
READ, WRITE, NOTIFY -> C++ and QML
If you would like to avoid programming trivial getters and setters, define your own makro wrapping Q_PROPERTY.
I provide a SDK to my users, allowing them to write DLLs in C++ for expanding the software.
The SDK headers mostly contain interface class definitions. These class are of two types:
Some that the user must subclass and implement
Some that are wrappers to core classes, passed by the app to the DLL functions as pointers, which can then be used as arguments by the DLL code for calling core functions. These interfaces should not be subclassed by the user and passed to the core functions, as they expect a specific core subclass.
I write in the manual the interfaces that should not be subclassed, and only used through pointers on objects provided by the app. But at some places, it's too tempting to subclass them in the SDK if you do not read the manual.
Would it be possible to prevent subclassing some interfaces in the SDK headers?
As long as the client doesn't need to use the pointer for anything but
passing it back into your DLL, you can just use a forward declaration;
you can't derive from an incomplete type. (When faced with a similar
case recently, I went whole hog, and designed a special wrapper type
based on void*. There's a lot of casting in the interface code, but
there's no way the client can do much other than pass the value back to
me.)
If the classes in question implement an interface which the client must
also use, there are two solutions. The first is to change this,
replacing each of the member functions with a free function which takes
a pointer to the type, and just provide a forward declaration. The
second is to use something like:
class InternallyVisibleInterface;
class ClientVisibleInterface
{
private:
virtual void doSomething() = 0;
ClientVisibleInterface() = default;
friend class InternallyVisibleInterface;
protected: // Or public, depending on whether the client should
// be able to delete instances or not.
virtual ~ClientVisibleInterface() = default;
public:
void something();
};
and in your DLL:
class InternallyVisibleInterface : public ClientVisibleInterface
{
protected:
InternallyVisibleInterface() {}
// And anything else you need. If there is only one class in
// your application which should derive from the interface,
// this is it. If there are several, they should derive from
// this class, rather than ClientVisibleInterface, since this
// is the only class which can construct the
// ClientVisibleInterface base class.
};
void ClientVisibleInterface::something()
{
assert( dynamic_cast<InternallyVisibleInterface*>( this ) != nullptr );
doSomething();
}
This offers two levels of protection: first, although derivation
directly from ClientVisibleInterface is possible, it's impossible for
the resulting class to have a constructor, and so it cannot be
instantiated. And secondly, if the client code does cheat somehow,
there will be a runtime error if he does so.
You probably don't need both protections; one or the other should
suffice. The private constructor will result in a compile time error,
rather than a runtime one. On the other hand, without it, you don't
even have to mention the name of InternallyVisibleInterface in the
distributed headers.
As soon as a developper has a developpement environment, he can do almost anything, and you should not even try to control that.
IMHO the best you can do is to identify the limit between the core application and the extension DLLs and ensure that objects received from those DLLs are or correct class, and abort with a distinctive message if they are not.
Using RTTI and typeid is generally frowned upon because it is generally the sign of a bad OOP design : in normal use case, calling virtual method is enough to have proper code invoked. But I think it can safely be considered in your use case.
I'm working on a sound library (with OpenAL), and taking inspiration from the interface provided by FMOD, you can see the interface at this link.
I've provided some concepts like: Sound, Channel and ChannelGroup, as you can see through FMOD interface, all of those classes have a private constructor and, for example, if you would create a Sound you mast use the function createSound() provided by the System class (the same if you would create a Channel or a ChannelGroup).
I'd like to provide a similar mechanism, but I don't understand how it work behind. For example, how can the function createSound() create a new istance of a Sound? The constructor is private and from the Sound interface there aren't any static methods or friendship. Are used some patterns?
EDIT: Just to make OP's question clear, s/he is not asking how to create a instance of class with private constructor, The question is in the link posted, how is instance of classes created which have private constructor and NO static methods or friend functions.
Thanks.
Hard to say without seeing the source code. Seems however that FMOD is 100% C with global variables and with a bad "OOP" C++ wrapper around it.
Given the absence of source code and a few of the bad tricks that are played in the .h files may be the code is compiled using a different header file and then just happens to work (even if it's clearly non-standard) with the compilers they are using.
My guess is that the real (unpublished) source code for the C++ wrapper is defining a static method or alternatively if everything is indeed just global then the object is not really even created and tricks are being played to fool C++ object system to think there is indeed an object. Apparently all dispatching is static so this (while not formally legal) can happen to work anyway with C++ implementations I know.
Whatever they did it's quite ugly and non-conforming from a C++ point of view.
They never create any instances! The factory function is right there in the header
/*
FMOD System factory functions.
*/
inline FMOD_RESULT System_Create(System **system)
{ return FMOD_System_Create((FMOD_SYSTEM **)system); }
The pointer you pass in to get a System object is immediately cast to a pointer to a C struct declared in the fmod.h header.
As it is a class without any data members who can tell the difference?
struct Foo {
enum Type {
ALPHA,
BETA_X,
BETA_Y
};
Type type () const;
static Foo alpha (int i) {return Foo (ALPHA, i);}
static Foo beta (int i) {return Foo (i<0 ? BETA_X : BETA_Y, i);}
private:
Foo (Type, int);
};
create_alpha could have been a free function declared friend but that's just polluting the namespace.
I'm afraid I can't access that link but another way could be a factory pattern. I'm guessing a bit, now.
It is the factory pattern - as their comment says.
/*
FMOD System factory functions.
*/
inline FMOD_RESULT System_Create(System **system) { return FMOD_System_Create((FMOD_SYSTEM **)system); }
It's difficult to say exactly what is happening as they don't publish the source for the FMOD_System_Create method.
The factory pattern is a mechanism for creating an object but the (sub)class produced depends on the parameters of the factory call. http://en.wikipedia.org/wiki/Factory_method_pattern
I have an ESB. Any serialized message transports its own fully qualified name (that is, namespace + class name). I have a concrete type for each message that encapsulates a specific logic to be executed.
Every time I receive a message, I need to deserialize it at first, so I can perform its operations --once more, depending on its concrete type--.
I need a way to register every single class at compile time or during my application initialization.
With .net I would use reflection to scan assemblies and discover the message types during initialization, but how would you do it in C++?
C++ has no reflection capability. I suppose you could try to scan object files, etc., but there's no reliable way to do this (AFAIK); the compiler may entirely eliminate or mangle certain things.
Essentially, for serialization, you will have to do the registration (semi-)manually. But you may be interested in a serialization library that will help out with the chores, such as Boost Serialization.
Since there is no reflection in C++, I would suggest using an external script to scan your source code for all relevant classes (which is easy if you use empty dummy #defines to annotate them in the source code) and have it generate the registration code.
I personally use the manual registration road. If you forget to register... then the test don't work anyway.
You just have to use a factory, and implement some tag dispatching. For example:
typedef void (*ActOnMessageType)(Message const&);
typedef std::map<std::string, ActOnMessageType> MessageDispatcherType;
static MessageDispatcherType& GetDispatcher() {
static MessageDispatcherType D; return D;
}
static bool RegisterMessageHandler(std::string name, ActOnMessageType func) {
return GetDispatcher().insert(std::make_pair(name, func)).second;
}
Then you just prepare your functions:
void ActOnFoo(Message const& m);
void ActOnBar(Message const& m);
And register them:
bool const gRegisteredFoo = RegisterMessageHandler("Foo", ActOnFoo);
bool const gRegisteredBar = RegsiterMessageHandler("Bar", ActOnBar);
Note: I effectively use a lazily initialized Singleton, in order to allow decoupling. That is the registration is done during the library load and thus each Register... call is placed in the file where the function is defined. The one difference with a global variable is that here the dispatching map is actually constant once the initialization ends.