I'm writing a program that has a portable C++ backend that we want to create a WinRT Xaml frontend for. I want to keep our models in pure C++ code and create a view in C++/CX that mirrors the C++ model that we can pass around and consume on the frontend. Is there any standard method for this?
For example:
class Person
{
public:
const std::wstring GetName() const;
void SetName(const std::wstring& value);
private:
std::wstring m_Name;
}
ref class PersonMirror : INotifyPropertyChanged
{
public:
property Platform::String^ Name
{
Platform::String^ get();
void set(Platform::String^ value);
}
private:
std::shared_ptr<Person> m_Person;
}
Some things I don't know how to do in this are:
How I get the associated ref mirror class from the native class. can I convert a void* to a PersonMirror^ and talk to the GC about holding a reference to the object?
Are there C++ implementations for triggering events? Or I guess if I can maintain that this is a 1-to-1 relationship, I can just use a function pointer perhaps?
You cannot simply convert a void* to a PersonMirror^. You have to use "ref new" to create a WinRT instance of the class and then copy the data (or a pointer to it) from Person into the PersonMirror. You can have a PersonMirror constructor that copies individual fields from the ISO C++ class, or you can just copy a shared_ptr as you have done, and provide public accessors for it in your ref class. This is a nice approach. Note: There is no "GC" in C++/CX; a ref class is basically just a smart pointer.
• You can use whatever eventing mechanism you like between a ref class and an ISO C++ class in the same process. The only restriction is that any public types in the ref class must be WinRT compatible. To expose a callback or function object event handler in PersonMirror, give it internal accessibilty so that it is invisible to the WinRT interface, but your ISO code can still access it.
The Reversi sample on MSDN demonstrates an ISO C++ class that is wrapped by a C++/CX wrapper class.
Related
I am in the midst of creating the architecture for my new Point and Click game in the Starling framework. It is set to be big in size, so I am trying to make sure to use best Object Oriented practises to ensure I do not A) Repeat the same methods. B) Keep it sustainable and clean.
I was unaware of Interfacing as a way to contract all classes. To keep everything consistent and to ensure that sub classes have the methods to function correctly. Let us look at an example of a player class i have created.
public interface IPlayer {
function changeDirection():void;
function walkToPosition():void;
function pickUpItem():void;
}
class AbstractPlayer extends Sprite implements IPlayer {
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
class Player extends AbstractPlayer {
override protected function walkToPosition():void {}
override protected function pickUpItem():void {}
}
I am aware that AS3 Does not support Abstract Classes natively. But I choose to have it in this form as it makes sense to. What I do not understand is why the interfaces only support public methods. Doesn't that defeat the whole purpose of having an interface; so you know what methods are needed for a player. Declaring only the public functions of the player class seems like a half job.
A verbose explanation of this concept and perhaps a more advanced solution to how this could be structured would be of great benefit.
Many Thanks,
Shaun
An interface is a collection of method declarations that allows unrelated objects to communicate with one another.Hence public access control identifiers for implemented methods.In a typical interactive context often a need arises to modify or control behavior of an object in question externally.In such a case, behavior-control may ideally be accomplished through an interface.Obliviously only methods put into a public namespace are accessible externally.Bearing in mind that attributes of an object should not be be directly modified by external code but only through an interface is good practice of Object Oriented Design. Assuming that a need arises of an object to have more than one point of access control(behavior control); one for external purposes and the other for internal purposes respectively, then putting all behavior in one interface defeats the objective.The following may help to achieve the objective(because you said it's big in size).
Put behavior in an interface you think should be accessible externally.
Define Mediator to encapsulate view-code-mediation:-listen for user triggered events, update view send notifications to other tiers of the application.
Define Model for data purposes.
Define executable commands to be called within your application.
See if you can promote as much lose coupling as possible among the tiers.The goal is to write as much less code as possible and not boiler-plate in nature.I recommend that you use a framework such as robotlegs if really your project is that big.The framework will take care of dependency injection and along the way lift off the burden of writing boiler-plate code.
I Hope the foregoing helps. Thanks.
The interface is acting as an outline of required members to be implemented in the classes using said interface. Therefore the interface methods never being called directly and only being used in the classes implementing them require no access modifiers.
Now you're correct AS3 does not support abstract classes, BUT there is a way to implement an "abstract" class AS3 as per the design. So here is what that might look like with your code:
public interface IPlayer
{
function init():void;
function changeDirection():void;
function walkToPosition():void;
function pickUpItem():void;
}
public class AbstractPlayer extends Sprite implements IPlayer
{
public function AbstractPlayer() {
init();
}
protected function init():void {
throw new IllegalOperationError( "Abstract method, must be overridden in subclass" );
}
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
public class Player extends AbstractPlayer
{
public function Player() {
super();
}
override protected function init():void {
//implementation
}
}
Abstract classes having method implementation by default will require subclasses to override these methods ( see init() and error thrown ) keeping strict usage of the parent class method and members.
This is the basic abstract class design for AS3. This is also the begining to a Factory Method pattern which you can read more on here: http://www.adobe.com/devnet/actionscript/articles/ora_as3_design_patterns.html
Now the more reusable design for this might be to generalize your class names a bit more, perhaps something more like this:
public interface IEntity
{
function init():void;
function changeDirection():void;
function walkToPosition():void;
}
This would be assuming that more game objects other than your Player class will have use of the methods in the IEntity interface.
Now your Player class can become a new object of type Entity:
public class Entity extends Sprite implements IEntity
{
public function Entity() {
init();
}
protected function init():void {
throw new IllegalOperationError( "Abstract method, must be overridden in subclass" );
}
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
Now in regards to the design, since abstract classes are just a tool like any other there are many different designs to take using it and it really depends on your project. I would recommend sifting through the aforementioned link to the "Factory Method" pattern and some of the other designs to see what fits your needs.
An interface defines the way other classes interact with a specific implementation of that interface. Other classes cannot call implementation's private methods directly - there's no need for the interface to define them.
Let's say we have two subclasses of AbstractPlayer: Player and AIPlayer. The Player class would probably include methods to listen for specific input events and to respond to them accordingly, like onKeyUp or onMouseClick, which should be private: there's no need to external classes to know how the player is controlled. The AIPlayer on the other hand is controlled by some strategies you define in your code, therefore instead of listening to user's input, it should keep track of Player's actions and react accordingly. This class does not need onKeyUp or onMouseClick methods, so why put them in interface?
By the looks of Google it seems like this might not be possible, but:
How do I define an 'out' parameter in a C++/CX 'ref class'?
If your answer is that this isn't possible, please provide a reference.
Any parameter which is of type T* (where T is a ABI-legal type) will be treated by the compiler as an out parameter, and decorated in metadata as such. The following code:
namespace TestMakePublic {
public ref class Class1 sealed
{
public:
void foo(int* out1, Object^* out2){}
};
}
Produces a function in metadata which looks like this (ildasm output):
.method public hidebysig newslot virtual final
instance void foo([out] int32& out1,
[out] object& out2) runtime managed
{
.override TestMakePublic.__IClass1PublicNonVirtuals::foo
} // end of method Class1::foo
Note that WinRT does not support "in/out" parameters, so the value of out1 and out2 are only valid for returning from the function, and cannot be trusted as inputs to foo.
It is a C# specific keyword, COM has it too in the IDL syntax. The equivalent in MSVC++ is the [out] attribute.
But no, the compiler is going to reject that with C3115 if you try to use it. Keep in mind that you use the C++/CX language extension to write code that's used by other languages. Which in general support to notion of [out] very poorly. Neither C++, Javascript or .NET languages like vb.net support it. You can see this as well in the .h files in C:\Program Files (x86)\Windows Kits\8.0\Include\WinRT, generated from the .idl files in that same directory that does have the [out] attribute. It was stripped in the .h file by midl.
It doesn't matter anyway since your code will be used in-process so there's no benefit at all from [out] being able to optimize the marshaling of the argument value. Just a plain pointer gets the job done. Having to initialize the argument value in C# code is however inevitable lossage.
You can use:
_Out_opt_
_Out_
But these are available only for private, internal, and protected members AFAIK.
I'm interested in calling a C# method from C++ code in Windows Phone 8. I have already learned how to pass a callback function to C++ code from C# via delegate declarations in my C++ code, but I am looking to see if I can do any of the following:
Call certain methods directly from the C++ code. This would involve somehow inspecting the C# object makeup from C++, and seems unlikely to me, but I thought I'd ask you all anyway
Trigger events in the C# code, which can then be handled by C# methods
Use a dispatcher to call C# callbacks in the Main UI thread so that the callbacks can modify UI elements
Use a dispatcher to trigger events in the C# code, (Essentially a merging of the above two points)
In short, I am looking for as many C++ -->C# communication tips as you guys can throw me, I want to learn it all. :)
By getting an object in C# code to implement a Windows RT interface, and passing down a reference to this object, it is possible to do all of the above with a bit of set-up (if I understand correctly - not sure about exactly what you want to do with your Dispatcher examples - you might want to wrap the Dispatcher on the C# side).
Create a Windows Runtime component library.
Define a public interface class in a C++/CX header for the C# to implement (C++ to call) (e.g. ICallback).
Define a public ref class in a C++/CX header for the C++ to implement (C# to call) (e.g. CppCxClass).
Add a method in CppCxClass that passes and stores an ICallback. (A C++ global variable is shown for consiseness, I recommend you review this to see if you can find a better place to store this in your code-base).
ICallback^ globalCallback;
...
void CppCxClass::SetCallback(ICallback ^callback)
{
globalCallback = callback;
}
Reference the WinRT library in your C# code.
C# code: create an instance of CppCxClass using var cppObject = new CppCxClass().
C# code: create a class which implements ICallback (e.g. CSharpCallbackObject).
C# code: pass an instance of CSharpCallbackObject down to C++. E.g. cppObject.SetCallback(new CSharpCallbackObject()).
You can now call C# with globalCallback->CallCsharp(L"Hello C#");. You should be able to extend either ICallback and/or CppCxObject to do the rest of your tasks.
After a lot of headaches trying to figure out the required code, I think it's worth posting the final version here
C++/CX
//.h
[Windows::Foundation::Metadata::WebHostHidden]
public interface class ICallback
{
public:
virtual void Exec( Platform::String ^Command, Platform::String ^Param);
};
//.cpp
ICallback ^CSCallback = nullptr;
void Direct3DInterop::SetCallback( ICallback ^Callback)
{
CSCallback = Callback;
}
//...
if (CSCallback != nullptr)
CSCallback->Exec( "Command", "Param" );
C#
public class CallbackImpl : ICallback
{
public void Exec(String Command, String Param)
{
//Execute some C# code, if you call UI stuff you will need to call this too
//Deployment.Current.Dispatcher.BeginInvoke(() => {
// //Lambda code
//}
}
}
//...
CallbackImpl CI = new CallbackImpl();
D3DComponent.SetCallback( CI);
Please retag this question to include languages to which it is relevant
So my java book had a whole chapter on nested classes, but ended on the note that you should only really use them when it comes to "modeling composition relationships and implementing internals of a class you want to hide". So lets discuss when you would want to use nested classes and some examples.
A nested/inner class is just a class that's only ever used specifically in the context of another class, which doesn't have it's own class file. If it's linked to an instance, it can only be instantiated in the context of a parent class instance; it can see private data, or only private static data if it's a static class.
The java developer site has a nested classes tutorial with one example:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
A couple examples of usage:
Hide a concrete implementation of an
interface:
(Thinking of a database session for a tool like Hibernate): Suppose you have a Session interface, and a SessionFactory which returns an instance of a Session. The SessionImpl concrete class that implements the Session interface could be an innner class of the factory that knows how to construct and initialize it.
Supply information by implementing an
interface:
In the Wicket web framework, each GUI component has an associated "model", whose job is to wire data to the component. The interface looks something like:
public interface IModel extends IDetachable {
public Object getObject();
public Object setObject();
}
Suppose you have some special logic to retrieve data for a custom GUI component that you've written. Since no other component retrieves data the same way, you could use an anonymous class at the point where the IModel is supplied to take care of the data retrieval. If you have another point in the same class where you need to reuse your IModel implementation, you could make it an inner class. Later, if you need the model elsewhere, you could convert it to a top-level class.
Generally you use an inner class in a situation where you need a class definition, but that class is only usable or only makes sense in the context of the parent class.
A real life usage i had with nested classes, was in a global settings object.
The parent class was a Singleton, with nested classes as settings categories.
Settings
File settings
Print settings
Etc.
There was no real point in making the inner object as separate classes, as their would be no use for them outside the settings class scope.
I use nested classes for encapsulating algorithms that would be usually done as a method with lots of arguments. I use class that has raw data and I put algorithms into separate file in nested class (using partial keyword). That way I can put properties for that algorithm and its (working) data lives after algorithm is done.
I know that can be easily done without nested classes but this feels right because algorithm is purposely built for parent class.
public partial class Network
{
partial void initFDLF()
{
fdlf=new FDLF(this);
}
public FDLF fdlf;
public class FDLF
{
internal bool changed=true;
internal bool pvchange=true;
public double epsilon = 0.001;
public bool fdlfOk=false;
public void init(){...}
public void run(){...}
...
I'm currently working my way through Code Complete and the word "interface" keeps popping up! I'm trying to get my head round what an interface is. Can you define the term? Also what actually makes up a "class interface"?
In general, an interface is simply "what the class looks like to the rest of the world".
For example, this class in Java:
class MyClass {
private string data;
private string Foo() {...}
public void Bar(string s){...}
}
could be said to have just the Bar function in its interface. Internally it has a few other members, but they're private, so they're not visible to the outside world.
More commonly, interfaces are also specific types in the language, for example in the following, MyClass implements the interface IMyClass:
interface IMyClass {
public void Bar(string s);
}
class MyClass implements IMyClass {
private string data;
private string Foo() {...}
public void Bar(string s){...}
}
The interface is now expressed in code, so that any time a variable of type IMyClass is expected, an object of type MyClass can be used, because it implements the correct interface.
I think a good way to define an interface is as follows
An interface is a contract specifying a set of methods, fields and properties which will be available on any implementing object
The actual implementation from language to language may have funny little differences but the principle holds.
I considered adding implemented interfaces to the list above but left it off because it seemed to be a bit too language specific. I think it's OK though because the end effect is almost the same. Tacking on more interfaces is just adding more methods, fields and properties to the contract.
The interface to a class is its "public face" that other classes can see. It separates the the class's implementation from the way it interacts with other classes. That way different implementations can be swapped out and other classes don't need to know anything about what's behind the interface.
An interface can include both data and function members.
It's external face to the world. Usually the set of public methods (members) it exposes.
Technically however they would be 2 different things
An interface would be a public contract. e.g.
interface ILogger
{
void Log(String str);
}
A class would then 'implement' this interface - in a way saying that it provides this functionality
class ConsoleLogger : ILogger
{
public ConsoleLogger() { ... }
public void Log(String str)
{
Console.WriteLine("Console Logger " + str);
}
// private stuff
}
Users of this service / interface do not have to concern themselves with how it is implemented or who is implementing it? By depending on an interface, the actual implementation can be switched at will.
Interface is definition of set of methods that class can impelement. It's mostly used for interface polymorphism.
A interface is like a class but not quite. It has similar traits like a class but it is not an interface. An interface has a variables and methods, "just like the class but the methods declared in interface are by default abstract (only method signature, no body)".
http://beginnersbook.com/2013/05/java-interface/
Interfaces have two definitions. It depends in what context the term Interface is used.
A Classes Interface refers to all the implemented public methods of a class.
An Interface as a Type. i.e using the keyword interface to declare an Interface.
interface Movable{
moveStraight();
moveLeft();
moveRight();
stop();
}
So now a class, lets say, Car can implement the interface Movable. This is what is know as the contract. If class Car implements interface Movable, Car guarantees to provide implementations for all the methods declared in Movables
declaration.
To conclude, generally an Interface is addressed as a type (definition 2) in a language specific programming context. You will find the first definition on fewer occasions usually in a theoretical or design context.
The classical real life example of an interface is the controls a car.
The break, gas, and wheel would be the interface.
The engine and other mechenical aspects would be the implementation.
These mechanical aspects can change, we wouldn't know because our interface remains the same.
This is the power of an interface, it hides implementation details so we can work on a higher level of abstraction. We can directly use the functionality of the interface usually without worrying about how the code underneath it is implemented.