Basically, I don't know much C++, and I've been trying to implement the leaderboard code from the friendSmasher sample project on github. After searching for some related posts, I found this post which recommended creating an Objective-C class to manage the data instead. Below is the relevant code from the project. How can I make an objective-c class(es) to manage the data?
struct LeaderboardboardInstance
{
System::Sprite* pStubSprite;
UILabel *pFriendName;
UILabel *pFriendScore;
System::TextureResource* pUserTexture;
System::Sprite* pUserSprite;
};
Also I believe the System::Sprite* abc and the other System calls are C++ libraries and would like to know the equivalent classes in Objective-C that I should use.
Related
I am searching for a simple, light-weight solution for interface-based runtime object composition in C++. I want to be able to specify interfaces (methods declarations), and objects (creatable through factory pattern) implementing these. At runtime I want mechanisms to instantiate these objects and interconnect these based on interface-connectors. The method calls at runtime should remain fairly cheap, i.e. only several more instructions per call, comparable to functor patterns.
The whole thing needs to be platform independent (at least MS Windows and Linux). And the solution needs to be licensed liberally, like open source LGPL or (even better) BSD or something, especially allowing use commercial products.
What I do not want are heavy things like networking, inter-process-communication, extra compiler steps (one-time code generation is ok though), or dependencies to some heavy libraries (like Qt).
The concrete scenario is: I have such a mechanism in a larger software, but the mechanism is not very well implemented. Interfaces are realized by base classes exported by Dlls. These Dlls also export factory functions to instantiate the implementing objects, based on hand-written class ids.
Before I now start to redesign and implement something better myself, I want to know if there is something out there which would be even better.
Edit: The solution also needs to support multi-threading environments. Additionally, as everything will happen inside the same process, I do not need data serialization mechanisms of any kind.
Edit: I know how such mechanisms work, and I know that several teaching books contain corresponding examples. I do not want to write it myself. The aim of my question is: Is there some sort of "industry standard" lib for this? It is a small problem (within a single process) and I am really only searching for a small solution.
Edit: I got the suggestion to add a pseudo-code example of what I really want to do. So here it is:
Somewhere I want to define interfaces. I do not care if it's C-Headers or some language and code generation.
class interface1 {
public:
virtual void do_stuff(void) = 0;
};
class interface2 {
public:
virtual void do_more_stuff(void) = 0;
};
Then I want to provide (multiple) implementations. These may even be placed in Dll-based plugins. Especially, these two classes my be implemented in two different Dlls not knowing each other at compile time.
class A : public interface1 {
public:
virtual void do_stuff(void) {
// I even need to call further interfaces here
// This call should, however, not require anything heavy, like data serialization or something.
this->con->do_more_stuff();
}
// Interface connectors of some kind. Here I use something like a template
some_connector<interface2> con;
};
class B : public interface2 {
public:
virtual void do_more_stuff() {
// finally doing some stuff
}
};
Finally, I may application main code I want to be able to compose my application logic at runtime (e.g. based on user input):
void main(void) {
// first I create my objects through a factory
some_object a = some_factory::create(some_guid<A>);
some_object b = some_factory::create(some_guid<B>);
// Then I want to connect the interface-connector 'con' of object 'a' to the instance of object 'b'
some_thing::connect(a, some_guid<A::con>, b);
// finally I want to call an interface-method.
interface1 *ia = a.some_cast<interface1>();
ia->do_stuff();
}
I am perfectly able to write such a solution myself (including all pitfalls). What I am searching for is a solution (e.g. a library) which is used and maintained by a wide user base.
While not widely used, I wrote a library several years ago that does this.
You can see it on GitHub zen-core library, and it's also available on Google Code
The GitHub version only contains the core libraries, which is really all the you need. The Google Code version contains a LOT of extra libraries, primarily for game development, but it does provide a lot of good examples on how to use it.
The implementation was inspired by Eclipse's plugin system, using a plugin.xml file that indicates a list of available plugins, and a config.xml file that indicates which plugins you would like to load. I'd also like to change it so that it doesn't depend on libxml2 and allow you to be able to specify plugins using other methods.
The documentation has been destroyed thanks to some hackers, but if you think this would be useful then I can write enough documentation to get you started.
A co-worker gave me two further tips:
The loki library (originating from the modern c++ book):
http://loki-lib.sourceforge.net/
A boost-like library:
http://kifri.fri.uniza.sk/~chochlik/mirror-lib/html/
I still have not looked at all the ideas I got.
I know that isn't exactly possible in C++, but maybe a toolchain that can generate code which has a function, which when called gives me a list of all those classes. For example, across multiple files I have stuff like:
class MyClass : public ParticularClass {
....
}
class MyClass2 : public ParticularClass {
....
}
Then, during runtime, I just want a pointer to single instances of the class. Let's say my generated code looks something like this:
void __populate_classes() {
superList.append(new MyClass());
superList.append(new MyClass2());
}
Also, superList would be of type List<ParticularClass*>. Plus, I'll be using Qt and ParticularClass will be QObject derived, so I can fetch the name of the class anyways. I need to basically introspect the class, so my internal code doesn't really bother much about the newly defined type.
So, is there a way to generate this code with some toolchain? If it is possible with qmake alone, that'd be like icing on the freaking cake :)
Thanks a lot for your time.
Doxygen does a nice job at doing this -- offline. Various IDEs do a nice job at this -- offline. The compiler does not do this. Such knowledge is not needed or used by the compiler.
Here at work I use a tool called Understand 4 C++. It is a tool that helps you analyze your code. It will do this quite easily.
But my favorite part is it comes with a C and Perl API which allows you to take advantage of the abstract syntax tree that 'understand' encapsulates and write your own static analysis tools. I have written tons of tools using this API.
Anyways, it's written by SciTools. http://scitools.com and I don't work for them. I just wholeheartedly like their product. In fact I wrote a C# API that wraps their C API and posted it on CodePlex a few years ago. Sure beats using C or Perl to write static analysis tools.
I don't think what you're trying to do is a good idea. Those who will maintain code after you will have hard times to understand it.
Maybe instead of it you'll try see how you can do it in plan C++. One possible solution which comes to mind i to implement factory design pattern. Than you can iterate over all data types in factory and add then to superList.
Any way, using ack (simple grep replacement) can do the job if you always declare the inheritence in one line:
ack ": *public ParticularClass" *.h
I'm currently refactoring a Tcl plugin library written in C++. Originally the code was hand-written. A second library exists that does the same thing for Java.
The refactored library will be a single C++ library that can be used to create bindings to different languages.
My first tests with SWIG are promising. However, a lot of junk is generated as well. Various base classes and utilities are all exported. These don't make sense from the scripting point of view and only increase clutter.
Possible solutions that I can think of are:
Use #ifndef SWIG in the original codebase to filter out unneeded code
Create a SWIG-compatible wrapper around the API classes.
Differentiate between public and private headers. Public headers are pure abstract base classes that contain no implementation. The private headers inherit and implement them. Only SWIG the public headers.
The opposite of the above solution: inherit a SWIG-compatible class for each API class.
I'm currently leaning towards solution 3 at the moment. However, I'm not really certain so I'd like to know the SO community's opinion on this. Feel free to share your thoughts.
Update
I forgot to list one solution:
Code that should not exported by SWIG should probably not be in the public section of your class.
Perhaps this is the answer. I'll have another look on Monday.
Update
I settled with a solution. See my answer.
Any approach that means that the C++ library becomes less useful to the C++ user is not the ideal solution.
#ifdef SWIG in the middle of .hpp files: Muddies up your C++ with unnecessary cruft, so it's not ideal
SWIG Specific Interface: This is a viable option, but only makes sense if the code you want to expose to SWIG is significantly higher level then the base C++ API.
Public vs Private interface: Might make sense, but again you have to ask at what cost to the C++ user of the API? Are you limiting the public interface too much? Who has access to the private interface? Should the pImpl idiom be considered instead?
SWIG Compatible Class for each interface: Probably more work than necessary.
First and foremost, to keep your SWIG related code separate from the rest of the API.
You probably don't want to import the .hpp files directly into SWIG (if SWIG wasn't considered during the initial design of the library), but if you do, you want to use a SWIG .i file to help you clean up the mess. There are three basic approaches we use, each with different use cases.
First, direct inclusion. This is useful if you know your API is nice and clean and well suited for parsing by SWIG:
// MyClass.i
%{
#include "MyClass.hpp" // included for the generated .cxx file
%}
%include "MyClass.hpp" // included and parsed directly by SWIG
The second case is for code that is most of the way there. This is code that had SWIG taken into consideration, but really needed some stuff for the C++ user that we didn't want to expose to SWIG:
// MyClass.i
%{
#include "MyClass.hpp" // included for the generated .cxx file
%}
%ignore MyClass::someFunction(); // This function really just causes us problems
%include "MyClass.hpp" // included and parsed directly by SWIG
The third case, and probably the one you want to use, is to directly choose which functions you want to expose to SWIG.
// MyClass.i
%{
#include "MyClass.hpp" // included for the generated .cxx file
%}
// With this example we provide exactly as much information to SWIG as we want
// it to have. Want it to know the base class? Add it. Don't want it to know about
// a function? Leave it out. want to add a new function? %extend it.
class MyClass
{
void importantFunction();
void importantFunction2();
}
I'd use apprach #3 too. I'm using a similar approach in my projects, and it is used by COM too (interfaces inherithed by private implementation class).
It is really easy to detect errors and maintain code in that way! Unfortunately you will end implementing all functions as virtual, but it should not be a big issue...
Separating the interface will keep it really clean and understandable!
My final solution: simply SWIG the original code base. In order to avoid generation of non-relevant code I use the following techniques. In order of preference:
Make non-swig code private or protected. If it doesn't need to be swigged, then it probably doesn't need to be public.
If possible, change the original code to make it more compatible with SWIG. I replaced a curiously recurring template pattern with abstract base classes. I was willing to make that sacrifice for SWIG :)
Add %ignore statements to the interface file.
Use #ifndef SWIG to filter it out. I don't like to pollute my original code so I only use this as a last resort.
Concerning my previous ideas:
Create a SWIG-compatible wrapper around the API classes.
Differentiate between public and private headers. Public headers are
pure abstract base classes that
contain no implementation. The private
headers inherit and implement them.
Only SWIG the public headers.
The opposite of the above solution: inherit a SWIG-compatible class for
each API class.
All these solutions require writing SWIG-compatible wrapper code. This is a bit silly because you are ditching SWIG's the strongest selling point: automatic generation of wrapper code. If I write my own wrapper code for SWIG then I might just as well write regular JNI code.
That said, I realize that for some projects writing wrapper code may the most cost-efficient solution. However, I this was not the case in my situation.
I have an unmanaged C++ application (unmanaged meaning: not using anything of the the fancy .Net stuff). I want to extend it with some meta information, and it looks like I could use the concept of attributes.
What I actually try to achieve is the following.
Starting from something a simple class like this:
class Book
{
public:
...
private:
string m_name;
string m_author;
int m_year;
};
I want to build functionality that can access the 'meta information' of the class and use it to dynamically build logic on it, e.g.
a dialog containing 3 edit fields (name, author, year)
a data grid with 3 columns
serialization logic
logic that maps this class to a database table with 3 columns
...
I my wildest dreams I imagine modifying this class like this:
[id="Book"]
class Book
{
public:
...
private:
[id="Name", defaultValue="", maximumLength=100]
string m_name;
[id="Author", defaultValue="", maximumLength=100]
string m_author;
[id="Year", defaultValue=2000, minimum=1900]
int m_year;
};
And then being able to get this 'meta' information to build up dialogs, filling data grids, serializing and deserializing instances, ...
But, is the concept of attributes limited to .Net/managed code?
And if I could use attributes in unmanaged code, would it be possible to do something like this? And what is a good place to start? (examples, ...)
Also, can the same (or similar) concepts be found in other compilers, on other platforms?
I am using Visual Studio 2010 and, as said before, unmanaged/native C++.
Visual C++ for a while supported a similar attribute notation when defining COM objects. I think support was eventually dropped because programmers use C++ for COM implementation when they want complete control, and the compiler doing things magically outside the programmer's control runs counter to that.
OTOH IDL does still allow you to define metadata, it compiles to C++ source code along with a type library which contains the metadata, and it can be retrieved at runtime.
No. C++ does not have introspection or attributes.
Look into Boost Serialization for the serialization stuff, for the others you need to implement it manually, as far as I know.
I have a code base where many of the classes I implement derive from classes that are provided by other divisions of my company. Working with these other devisions often have the working relationship as though they are third party middle ware vendors.
I'm trying to write test code without modifying these base classes. However, there are issues with creating meaningful test
objects due to the lack of interfaces:
//ACommonClass.h
#include "globalthermonuclearwar.h" //which contains deep #include dependencies...
#include "tictactoe.h" //...and need to exist at compile time to get into test...
class Something //which may or may not inherit from another class similar to this...
{
public:
virtual void fxn1(void); //which often calls into many other classes, similar to this
//...
int data1; //will be the only thing I can test against, but is often meaningless without fxn1 implemented
//...
};
I'd normally extract an interface and work from there, but as these are "Third Party", I can't commit these changes.
Currently, I've created a separate file that holds fake implementations for functions that are defined in the third-party supplied base class headers on a need to know basis, as has been described in the book "Working with Legacy Code".
My plan was to continue to use these definitions and provide alternative test implementations for each third party class that I needed:
//SomethingRequiredImplementations.cpp
#include "ACommonClass.h"
void CGlobalThermoNuclearWar::Simulate(void) {}; // fake this and all other required functions...
// fake implementations for otherwise undefined functions in globalthermonuclearwar.h's #include files...
void Something::fxn1(void) { data1 = blah(); } //test specific functionality.
But before I start doing that I was wondering if any one has tried providing actual objects on a code base similar to mine, which would allow creating new test specific classes to use in place of actual third-party classes.
Note all code bases in question are written in C++.
Mock objects are suitable for this kind of task. They allow you to simulate the existence of other components without needing them to be present. You simply define the expected input and output in your tests.
Google have a good mocking framework for C++.
I'm running into a very similar problem at the moment. I don't want to add a bunch of interfaces that are only there for the purpose of testing, so I can't use any of the existing mock object libraries. To get around this I do the same thing, creating a different file with fake implementations, and having my tests link the fake behaviour, and production code links the real behaviour.
What I wish I could do at this point, is take the internals of another mock framework, and use it inside my fake objects. It would look a little something like this:
Production.h
class ConcreteProductionClass { // regular everyday class
protected:
ConcreteProductionClass(); // I've found the 0 arg constructor useful
public:
void regularFunction(); // regular function that I want to mock
}
Mock.h
class MockProductionClass
: public ConcreteProductionClass
, public ClassThatLetsMeSetExpectations
{
friend class ConcreteProductionClass;
MockTypes membersNeededToSetExpectations;
public:
MockClass() : ConcreteProductionClass() {}
}
ConcreteProductionClass::regularFunction() {
membersNeededToSetExpectations.PassOrFailTheTest();
}
ProductionCode.cpp
void doSomething(ConcreteProductionClass c) {
c.regularFunction();
}
Test.cpp
TEST(myTest) {
MockProductionClass m;
m.SetExpectationsAndReturnValues();
doSomething(m);
ASSERT(m.verify());
}
The most painful part of all this is that the other mock frameworks are so close to this, but don't do it exactly, and the macros are so convoluted that it's not trivial to adapt them. I've begun looking into this on my spare time, but it's not moving along very quickly. Even if I got my method working the way I want, and had the expectation setting code in place, this method still has a couple drawbacks, one of them being that your build commands can get to be kind of long if you have to link against a lot of .o files rather than one .a, but that's manageable. It's also impossible to fall through to the default implementation, since we're not linking it. Anyway, I know this doesn't answer the question, or really even tell you anything you don't already know, but it shows how close the C++ community is to being able to mock classes that don't have a pure virtual interface.
You might want to consider mocking instead of faking as a potential solution. In some cases you may need to write wrapper classes that are mockable if the original classes aren't. I've done this with framework classes in C#/.Net, but not C++ so YMMV.
If I have a class that I need under test that derives from something I can't (or don't want to) run under test I'll:
Make a new logic-only class.
Move the code-i-wanna-test to the logic class.
Use an interface to talk back to the real class to interact with the base class and/or things I can't or won't put in the logic.
Define a test class using that same interface. This test class could have nothing but noops or fancy code that simulates the real classes.
If I have a class that I just need to use in testing, but using the real class is a problem (dependencies or unwanted behaviors):
I'll define a new interface that looks like all of the public methods I need to call.
I'll create a mock version of the object that supports that interface for testing.
I'll create another class that is constructed with a "real" version of that class. It also supports that interface. All interface calls a forwarded to the real object methods.
I'll only do this for methods I actually call - not ALL the public methods. I'll add to these classes as I write more tests.
For example, I wrap MFC's GDI classes like this to test Windows GDI drawing code. Templates can make some of this easier - but we often end up not doing that for various technical reasons (stuff with Windows DLL class exporting...).
I'm sure all this is in Feather's Working with Legacy Code book - and what I'm describing has actual terms. Just don't make me pull the book off the shelf...
One thing you did not indicate in your question is the reason why your classes derive from base classes from the other division. Is the relationship really a IS-A relationshiop ?
Unless your classes needs to be used by a framework, you could consider favoring delegation over inheritance. Then you can use dependency injection to provide your class with a mock of their class in the unit tests.
Otherwise, an idea would be to write a script to extract and create the interface your need from the header they provide, and integrate this to the compilation process so your unit test can ve checked in.