Calling C# method from C++ code in WP8 - windows-phone-8

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);

Related

Call platform specific code from core project

I just Implemented ads for Android in my game using this guide.
It works fine, I have an interface in my core project that the Android Activity implements.
However my problem is that you need to send this implemented interface to the core project, and then pass it as a parameter to your first Screen, where you can use it, ex:
public MyGdxGame(PlatformSpecific ps) //Android class that handle fb-login and ads
{
this.ps = ps;
}
#Override
public void create ()
{
setScreen(new LoginScreen(this, ps);
}
This was fine for when I needed fb-login since I'm using that in the LoginScreen, but I want to be able to create my ads in other Screens (after a game is finished) by calling createAd-method in interface.
Do I have to keep passing ps between all the Screens just so I can use it in a Screen that only gets used quite rarely, or is there some way to get to this interface from my Screen without passing it to the constructor? Kind of like when you initiate an object, ex:
private PlatformSpecific ps = new PlatformSpecific();
Or does LibGdx have some library to support this scenario maybe? Worst case I could just pass ps between all constructors but feels like a pretty ugly solution.
Solution 1:
Store PlatformSpecific in a global static variable. That allows you to access anywhere in your code without passing it in every constructor.
Soluatio 2:
Have MyPlatformContext class which provides access to PlatformSpecific. Then pass this MyPlatformContext object to your screen constructors. If you extend your platform specific code later you do not have to change the screen constructors. Just edit MyPlatformContextMyPlatformContext class.
Pseudo code:
class MyPlatformContext {
private FacbookPlatform fb;
private AdmobPlatform admob
FacbookPlatform getFacebook() {
return fb;
}
...
}

CX view of C++ classes

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.

cocos2d-x c++ -> java for android

Currently I'am developing a game using cocos2d-x.
Of course, for multi-platform use.
basically I use a xcode for coding and development.
I want to attach IAP(In app purchases) separately to each coding for iPhone and Android
Problem to try to call a function of a certain class in Android that did not work.
Sources include the following:
cpp side
MyClass::invoke_init()
{
JavaVM* jvm = JniHelper::getJavaVM();
JNIEnv* env;
jvm->GetEnv((void **) &env, JNI_VERSION_1_2);
jclass cls;
jmethodID method;
cls = env->FindClass("com/joycestudios/game/SampleActivity");
method = env->GetMethodID(cls, "initFunc", "()V");
env->CallVoidMethod(cls, method);
}
java side
public class SampleActivity extends Cocos2dxActivity
{
public void initFunc()
{
Log.v("LOG_INFO", "initFunc()");
}
}
The first test as follows: I'm in progress.
build from xcode and build from build_natvie.sh and last build from eclipse.
But after run on eclipse, Just black screen and shuts down.
How to call a function of a java class?
What I looked at several samples, including also analyze the problem, I do not see any problems?
Can you tell if you find any error log?
First check if your game is working fine on android..
Den we can have a look how to call the function.
Generally for calling native method I use MessageJni class available in Cocos2d-x library.
I create my methods in MessageJni class which calls for native methods.
Its easy and convenient way of calling native methods.
Just google using MessageJni class. It will ease your work.
:)

How to replace PureMVC Standard with PureMVC MultiCore

I am working on a project, which uses PureMVC Standard. Now I need to add a new module SWF, which also uses Standard. I know the solution is to replace Standard MVC with MultiCore MVC, but there are two problems:
Standard's package structure is different from MultiCore's - do I have to correct this manually?
Under standard mvc framework, some code in the constructor of Mediator is allowed, while in MultiCore, this seems to be absolutely forbidden - so do I have to change so many constructors to get rid of this?
And finally: Other than replacing Standard with MultiCore, is there any better way to resolve the problem?
I am unaware of any other good methods for changing the package structure, other than global search-and-replace across a project. I have also not had problems doing this.
For Mediators, I have never had a problem with initializing simple variables (ints, Booleans, Arrays, etc) in the constructor, but anything else gets deferred to an onRegister (especially anything involving the stage in any way) and look something like:
public class MyMediator extends Mediator implements IMediator {
public static const NAME : String = "MyMediator";
// internal states
private var foo : int;
public function MyMediator (viewComponent : Object) {
super(NAME, viewComponent);
foo = 0;
trace("MyMediator()", main_mc);
}
override public function onRegister () : void {
main_mc.addEventListener(...);
}
protected function get main_mc () : Main {
return viewComponent as Main;
}
}
Having sparse contructors in AS3 is a good idea anyway, because constructor code is always interpreted and not compiled.
Out of habit now, I use multicore for all projects, even when I have a single core. This makes reusing mediators and proxies in new projects much easier.

Fluent Interfaces - Method Chaining

Method chaining is the only way I know to build fluent interfaces.
Here's an example in C#:
John john = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
Assert.IsNotNull(john);
[Test]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;
IInvoice invoice = new InvoiceBuilder()
.IssuedOn(now)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
.Generate();
Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}
So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?
The core idea behind building a fluent interface is one of readability - someone reading the code should be able to understand what is being achieved without having to dig into the implementation to clarify details.
In modern OO languages such as C#, VB.NET and Java, method chaining is one way that this is achieved, but it's not the only technique - two others are factory classes and named parameters.
Note also that these techniques are not mutually exclusive - the goal is to maximize readabilty of the code, not purity of approach.
Method Chaining
The key insight behind method chaining is to never have a method that returns void, but to always return some object, or more often, some interface, that allows for further calls to be made.
You don't need to necessarily return the same object on which the method was called - that is, you don't always need to "return this;".
One useful design technique is to create an inner class - I always suffix these with "Expression" - that exposes the fluent API, allowing for configuration of another class.
This has two advantages - it keeps the fluent API in one place, isolated from the main functionality of the class, and (because it's an inner class) it can tinker with the innards of the main class in ways that other classes cannot.
You may want to use a series of interfaces, to control which methods are available to the developer at a given point in time.
Factory Classes
Sometimes you want to build up a series of related objects - examples include the NHibernate Criteria API, Rhino.Mocks expectation constraints and NUnit 2.4's new syntax.
In both of these cases, you have the actual objects you are storing, but to make them easier to create there are factory classes providing static methods to manufacture the instances you require.
For example, in NUnit 2.4 you can write:
Assert.That( result, Is.EqualTo(4));
The "Is" class is a static class full of factory methods that create constraints for evaluation by NUnit.
In fact, to allow for rounding errors and other imprecision of floating point numbers, you can specify a precision for the test:
Assert.That( result, Is.EqualTo(4.0).Within(0.01));
(Advance apologies - my syntax may be off.)
Named Parameters
In languages that support them (including Smalltalk, and C# 4.0) named parameters provide a way to include additional "syntax" in a method call, improving readability.
Consider a hypothetical Save() method that takes a file name, and permissions to apply to the file after saving:
myDocument.Save("sampleFile.txt", FilePermissions.ReadOnly);
with named parameters, this method could look like this:
myDocument.Save(file:"SampleFile.txt", permissions:FilePermissions.ReadOnly);
or, more fluently:
myDocument.Save(toFile:"SampleFile.txt", withPermissions:FilePermissions.ReadOnly);
You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.
For example in C#:
public class JohnBuilder
{
public JohnBuilder AddSmartCode(string s)
{
// do something
return this;
}
public JohnBuilder WithfluentInterface(string s)
{
// do something
return this;
}
public JohnBuilder ButHow(string s)
{
// do something
return this;
}
}
Usage:
John = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
AFAIK, the term fluent interface does not specify a specific technology or framework, but rather a design pattern. Wikipedia does have an extensive example of fluent interfaces in C♯.
In a simple setter method, you do not return void but this. That way, you can chain all of the statements on that object which behave like that. Here is a quick example based on your original question:
public class JohnBuilder
{
private IList<string> languages = new List<string>();
private IList<string> fluentInterfaces = new List<string>();
private string butHow = string.Empty;
public JohnBuilder AddSmartCode(string language)
{
this.languages.Add(language);
return this;
}
public JohnBuilder WithFluentInterface(string fluentInterface)
{
this.fluentInterfaces.Add(fluentInterface);
return this;
}
public JohnBuilder ButHow(string butHow)
{
this.butHow = butHow;
return this;
}
}
public static class MyProgram
{
public static void Main(string[] args)
{
JohnBuilder johnBuilder = new JohnBuilder().AddSmartCode("c#").WithFluentInterface("Please").ButHow("Dunno");
}
}
Sometime ago I had the same doubts you are having now. I've done some research and now I'm writing a series of blog posts about techinics of designing a fluent interface.
Check it out at:
Guidelines to Fluent Interface design in C# part 1
I have a section there about Chaining X Nesting that can be interesting to you.
In the following posts I will talk about it in a deeper way.
Best regards,
André Vianna
Fluent interface is achieved in object oriented programming by always returning from your methods the same interface that contains the method. Consequently you can achieve this effect in java, javascript and your other favorite object oriented languages, regardless of version.
I have found this technique easiest to accomplish through the use of interfaces:
public interface IFoo
{
IFoo SetBar(string s);
IFoo DoStuff();
IFoo SetColor(Color c);
}
In this way, any concrete class that implements the interface, gets the fluent method chaining capabilities. FWIW.. I wrote the above code in C# 1.1
You will find this technique littered throughout the jQuery API
A couple of things come to mind that are possible in .Net 3.5/C# 3.0:
If an object doesn't implement a fluent interface, you could use Extension Methods to chain your calls.
You might be able to use the object initialization to simulate fluent, but this only works at instantiation time and would only work for single argument methods (where the property is only a setter). This seems hackish to me, but the there it is.
Personally, I don't see anything wrong with using function chaining if you are implementing a builder object. If the builder object has chaining methods, it keeps the object you are creating clean. Just a thought.
This is how I've built my so called fluent interfaces or my only forary into it
Tokenizer<Bid> tkn = new Tokenizer<Bid>();
tkn.Add(Token.LambdaToken<Bid>("<YourFullName>", b => Util.CurrentUser.FullName))
.Add(Token.LambdaToken<Bid>("<WalkthroughDate>",
b => b.WalkThroughDate.ToShortDateString()))
.Add(Token.LambdaToken<Bid>("<ContactFullName>", b => b.Contact.FullName))
.Cache("Bid")
.SetPattern(#"<\w+>");
My example required .net 3.5 but that's only cause of my lambda's. As Brad pointed out you can do this in any version of .net. Although I think lambda's make for more interesting possibilities such as this.
======
Some other good examples are nHibernate's Criteria API, there is also a fluent nhibernate extension for configuring nhibernate but I've never used it
Dynamic keyword in C# 4.0 will make it possible to write dynamic style builders. Take a look at following article about JSON object construction.