Unity3D embedded Mono with Unity - mono

I've seen plenty of examples of calling static methods in my Unity C# code using C++. I haven't however seen any examples of how to call a single instance's method using C++. i.e rather than
public static void SomeMethod(
{
}
I really want to do:
public void SomeMethod()
{
}
I've managed to make the static implementation work by following some tutorials from but would love to know if the bottom method is possible. I've tried to add a definition for searching a method in a class.
MonoMethod* mono_method_desc_search_in_class (MonoMethodDesc *desc, MonoClass *klass);
But an implementation can't be found with the mono runtime that I was told to use from here: http://www.reigndesign.com/blog/unity-native-plugins-os-x/
Any guidance or knowledge of whether it's possible or how to do it would be appreciated.
Edit:
One other question. If I search for a gameObject, could I then use that to access the instance?

You don't say what platform you're developing for, but for iOS there's the UnitySendMessage function. I believe there are similar implementations for other platforms.
http://docs.unity3d.com/Documentation/Manual/PluginsForIOS.html
Calling C# / JavaScript back from native code
Unity iOS supports limited native-to-managed callback functionality via UnitySendMessage:
UnitySendMessage("GameObjectName1", "MethodName1", "Message to send");
The parameter must be a string, so I've used JSON to send more complex data.
Alternatively, everything that inherits from UnityEngine.Object has a GetInstanceID() method, which is guaranteed to be unique. Using this you could have a static method in C# that keeps a dictionary of recipient instances, and native code would always pass an integer ID to refer to the intended recipient.
static Dictionary<int, SomeClass> instanceDict = new Dictionary<...>();
void Awake() {
instanceDict.Add(GetInstanceID(), this);
}
void OnDestroy() {
instanceDict.Remove(GetInstanceID());
}
public static void SomeMethod(int recipientID, float someValue) {
instanceDict[recipientID].SomeMethod(someValue);
}

Related

JavaFX Wrap an Existing Object with Simple Properties

I am writing a new app and I have chosen to use Java for flexibility. It is a GUI app so I will use JavaFX. This is my first time using Java but I have experience with C#.
I am getting familiar with JavaFX Properties, they look like a great way of bi-directional binding between front-end and back-end.
My code uses classes from an open-source API, and I would like to convert the members of these classes to JavaFX Properties (String => StringProperty, etc). I believe this would be transparent to any objects that refer to these members.
Is it ok to do this?
Is it the suggested way of dealing with existing classes?
What do I do about Enum types? E.g. an enum member has it's value changed, how should I connect the enum member to the front-end?
Thank you :)
In general, as long as you don't change the public API of the class - in other words you don't remove any public methods, modify their parameter types or return types, or change their functionality - you should not break any code that uses them.
So, e.g. a change from
public class Foo {
private String bar ;
public String getBar() {
return bar ;
}
public void setBar(String bar) {
this.bar = bar ;
}
}
to
public class Foo {
private final StringProperty bar = new SimpleStringProperty();
public StringProperty barProperty() {
return bar ;
}
public String getBar() {
return barProperty().get();
}
public void setBar(String bar) {
barProperty().set(bar);
}
}
should not break any clients of the class Foo. The only possible problem is that classes that have subclassed Foo and overridden getBar() and/or setBar(...) might get unexpected behavior if their superclass is replaced with the new implementation (specifically, if getBar() and setBar(...) are not final, you have no way to enforce that getBar()==barProperty().get(), which is desirable).
For enums (and other objects) you can use an ObjectProperty<>:
Given
public enum Option { FIRST_CHOICE, SECOND_CHOICE, THIRD_CHOICE }
Then you can do
public class Foo {
private final ObjectProperty<Option> option = new SimpleObjectProperty<>();
public ObjectProperty<Option> optionProperty() {
return option ;
}
public Option getOption() {
return optionProperty().get();
}
public void setOption(Option choice) {
optionProperty().set(choice);
}
}
One caveat to all this is that you do introduce a dependency on the JavaFX API that wasn't previously present in these classes. JavaFX ships with the Oracle JDK, but it is not a full part of the JSE (e.g. it is not included in OpenJDK by default, and not included in some other JSE implementations). So in practice, you're highly unlikely to be able to persuade the developers of the open source library to accept your changes to the classes in the library. Since it's open source, you can of course maintain your own fork of the library with JavaFX properties, but then it will get tricky if you want to incorporate new versions of that library (you will need to merge two different sets of changes, essentially).
Another option is to use bound properties in the classes, and wrap them using a Java Bean Property Adapter. This is described in this question.

How to get hold of AutomatedInstallData within IzPack 5 InstallerListener methods?

I've tried to find any info on that but failed, maybe someone here can help.
I'm using IzPack 5 since couple of weeks and that's what I started with, so I have no prior IzPack 4 experience.
What I want to do is the following:
Give the user an opportunity to select data directory via
UserInputPanel (works fine)
Validate the entry by checking if the
database already resides there (works fine)
Depending on whether
the DB already exists and if "force" flag specified on the
UserInputPanel create the database after the packs have been
installed
This last step, that's what I can't see how to do.
I hava a java class that implements InstallerListener interface:
public class IzPackInstaller implements com.izforge.izpack.api.data.DynamicInstallerRequirementValidator,
com.izforge.izpack.api.event.InstallerListener {
It's the same class I use for both data validation / db existance check on step 2 and creation on step 3, just for convinience reasons, but it shouldn't matter
I override
#Override
public void afterInstallerInitialization(AutomatedInstallData data)
throws Exception {
System.out.println("Called afterInstallerInitialization");
System.out.println("db.location=" + data.getVariable("db.location"));
System.out.println("db.force.creation=" + data.getVariable("db.force.creation"));
}
but it seems to be deprecated alltogether and is never called in runtime - checked with System.out's.
The same is valid for:
#Override
public void afterPacks(AutomatedInstallData data,
AbstractUIProgressHandler handler) throws Exception {
System.out.println("Never called!");
}
I also override
#Override
public void afterPacks(List<Pack> packs, ProgressListener listener) { }
which is called allright, but how to get hold of AutomatedInstallData within this method? Or how else can I read installer variables at this stage?
I thought of creating a singleton, which I would initialize with the variables during DynamicInstallerRequirementValidator.validateData() call and get the variables at a later point in time, but it's ugly and sounds like a nasty workaround - there should be a way to implement InstallerListener interface and be able to use the variables, shouldn't it?
I'd be really grateful for any hints...
Anton
This is not a very clean solution but there is a way to get a hold of AutomatedInstallData really anywhere in running izpack java without actually overriding some method etc. I would just not suggest it in the first place because it is a little tricky :)
public class Test {
InstallerContainer container = new ConsoleInstallerContainer();
AutomatedInstaller automatedInstaller = container.getComponent(AutomatedInstaller.class);
AutomatedInstallData installData;
public Test() throws IllegalAccessException, NoSuchFieldException {
Field f = AutomatedInstaller.class.getDeclaredField("installData");
f.setAccessible(true);
installData = (AutomatedInstallData)f.get(automatedInstaller);
}
etc...
Now you will have access to the object AutomatedInstallData and its methods.

Monkey Patching in C#

Is it possible to extend or modify the code of a C# class at runtime?
My question specifically revolves around Monkey Patching / Duck Punching or Meta Object Programming (MOP), as it happens in scripting languages such as Groovy, Ruby etc.
For those still stumbling on this question in the present day, there is indeed a present-day library called Harmony that relatively-straightforwardly enables such monkey-patching at runtime. Its focus is on video game modding (particularly games built with Unity), but there ain't much stopping folks from using it outside of that use case.
Copying the example from their introduction, if you have an existing class like so:
public class SomeGameClass
{
public bool isRunning;
public int counter;
private int DoSomething()
{
if (isRunning)
{
counter++;
}
return counter * 10;
}
}
Then Harmony can patch it like so:
using HarmonyLib;
using Intro_SomeGame;
public class MyPatcher
{
// make sure DoPatching() is called at start either by
// the mod loader or by your injector
public static void DoPatching()
{
var harmony = new Harmony("com.example.patch");
harmony.PatchAll();
}
}
[HarmonyPatch(typeof(SomeGameClass))]
[HarmonyPatch("DoSomething")]
class Patch01
{
static AccessTools.FieldRef<SomeGameClass, bool> isRunningRef =
AccessTools.FieldRefAccess<SomeGameClass, bool>("isRunning");
static bool Prefix(SomeGameClass __instance, ref int ___counter)
{
isRunningRef(__instance) = true;
if (___counter > 100)
return false;
___counter = 0;
return true;
}
static void Postfix(ref int __result)
{
__result *= 2;
}
}
Here, we have a "prefix" patch which gets inserted before the original method runs, allowing us to set variables within the method, set fields on the method's class, or even skip the original method entirely. We also have a "postfix" patch which gets inserted after the original method runs, and can manipulate things like the return value.
Obviously this ain't quite as nice as the sorts of monkey-patching you can do in e.g. Ruby, and there are a lot of caveats that might hinder its usefulness depending on your use case, but in those situations where you really do need to alter methods, Harmony's a pretty proven approach to doing so.
Is it possible to extend or modify the code of a C# class at run-time?
No it is not possible to do this in .NET. You could write derived classes and override methods (if they are virtual) but you cannot modify an existing class. Just imagine if what you were asking was possible: you could modify the behavior of some existing system classes like System.String.
You may also take a look at Extension methods to add functionality to an existing class.
You can add functionality, but you cannot change or remove functionality.
You can extend classes by adding extra methods, but you cannot override them because added methods have always lower priority than existing ones.
For more info, check Extension Methods in C# Programming Guide.

Persistence classes in Qt

I'm porting a medium-sized CRUD application from .Net to Qt and I'm looking for a pattern for creating persistence classes. In .Net I usually created abstract persistence class with basic methods (insert, update, delete, select) for example:
public class DAOBase<T>
{
public T GetByPrimaryKey(object primaryKey) {...}
public void DeleteByPrimaryKey(object primaryKey) {...}
public List<T> GetByField(string fieldName, object value) {...}
public void Insert(T dto) {...}
public void Update(T dto) {...}
}
Then, I subclassed it for specific tables/DTOs and added attributes for DB table layout:
[DBTable("note", "note_id", NpgsqlTypes.NpgsqlDbType.Integer)]
[DbField("note_id", NpgsqlTypes.NpgsqlDbType.Integer, "NoteId")]
[DbField("client_id", NpgsqlTypes.NpgsqlDbType.Integer, "ClientId")]
[DbField("title", NpgsqlTypes.NpgsqlDbType.Text, "Title", "")]
[DbField("body", NpgsqlTypes.NpgsqlDbType.Text, "Body", "")]
[DbField("date_added", NpgsqlTypes.NpgsqlDbType.Date, "DateAdded")]
class NoteDAO : DAOBase<NoteDTO>
{
}
Thanks to .Net reflection system I was able to achieve heavy code reuse and easy creation of new ORMs.
The simplest way to do this kind of stuff in Qt seems to be using model classes from QtSql module. Unfortunately, in my case they provide too abstract an interface. I need at least transactions support and control over individual commits which QSqlTableModel doesn't provide.
Could you give me some hints about solving this problem using Qt or point me to some reference materials?
Update:
Based on Harald's clues I've implemented a solution that is quite similar to the .Net classes above. Now I have two classes.
UniversalDAO that inherits QObject and deals with QObject DTOs using metatype system:
class UniversalDAO : public QObject
{
Q_OBJECT
public:
UniversalDAO(QSqlDatabase dataBase, QObject *parent = 0);
virtual ~UniversalDAO();
void insert(const QObject &dto);
void update(const QObject &dto);
void remove(const QObject &dto);
void getByPrimaryKey(QObject &dto, const QVariant &key);
};
And a generic SpecializedDAO that casts data obtained from UniversalDAO to appropriate type:
template<class DTO>
class SpecializedDAO
{
public:
SpecializedDAO(UniversalDAO *universalDao)
virtual ~SpecializedDAO() {}
DTO defaultDto() const { return DTO; }
void insert(DTO dto) { dao->insert(dto); }
void update(DTO dto) { dao->update(dto); }
void remove(DTO dto) { dao->remove(dto); }
DTO getByPrimaryKey(const QVariant &key);
};
Using the above, I declare the concrete DAO class as following:
class ClientDAO : public QObject, public SpecializedDAO<ClientDTO>
{
Q_OBJECT
public:
ClientDAO(UniversalDAO *dao, QObject *parent = 0) :
QObject(parent), SpecializedDAO<ClientDTO>(dao)
{}
};
From within ClientDAO I have to set some database information for UniversalDAO. That's where my implementation gets ugly because I do it like this:
QMap<QString, QString> fieldMapper;
fieldMapper["client_id"] = "clientId";
fieldMapper["name"] = "firstName";
/* ...all column <-> field pairs in here... */
dao->setFieldMapper(fieldMapper);
dao->setTable("client");
dao->setPrimaryKey("client_id");
I do it in constructor so it's not visible at a first glance for someone browsing through the header. In .Net version it was easy to spot and understand.
Do you have some ideas how I could make it better?
As far as I know there is nothing ready made that gives to this facility directly in qt. There are some possible approaches.
Implement the fields as Q_PROPERTY, the are then reflected through the Metaclass system and can be used to implement generic DAO functionality
You could still use the QSqlTableModel but encapsulate writes with transactions, if a transaction fails, refresh the model from the DB. Feasibility depends on the size of the data that you hold in the the model.
We currently use a TableModel/QSqlRecord based approach for reading and writing, there is no ORM mapping done in our system. I have been trying to engineer a more generic approach but the refactoring work that we would have to do to get there is to costly at the moment.
This link http://giorgiosironi.blogspot.com/2009/08/10-orm-patterns-components-of-object.html is not Qt related but a good overview of implementation patterns
If you want an ORM which only depends on Qt and builds upon Qt's Meta-Object System to provide instrospection, you might consider trying QDjango. On top of the basic create/update/delete operations at the model level, it provides a queryset template class (modeled after django's querysets) which allows to build fairly complex lookups. QtScript integration is also underway.
Tegesoft has recently release a new version of its library named CAMP that provide C++ runtime reflexion as you are using in .Net. I think this will allow you to achieve your application like you have done in .Net.
There is also a new open source ORM C++ library : QxOrm. QxOrm is based on QtSql Qt module to communicate with database and boost::serialization to serialize your data with xml and binary format. The web site is in french but quick sample code and tutorial code is in english (a translation is in progress...).
...And one more new Qt ORM: QST: QsT SQL Tools (latest stable version - 0.4.2a release).
QST provides mechanism to generate simple SQL queries: SELECT, INSERT, DELETE, UNPDATE and EXECUTE. Version 0.4 uses T-SQL; new version - 0.5 - will use PostgreSQL by default. You will find, this ORM based on original, unusual conceptions. For example, it integrated with Qt Interview system, so you can setting up view representation (column widths, titles) much easy.
There are example projects for versions 0.3 and 0.4: TradeDB 0.3, TradeDB 0.4. TradeDB 0.4 should be useful to start learning QST.
This seems like an excellent technique. I am, however, having some problems getting my prototype to compile n link....
I've implemented the basics as you describe and call the DAO class to retrieve an instance of one of my DB-resident objects.
Here are the statements calling this these model classes:
_db = <create QSqlDatabase>;
dao = new UniversalDAO (_db);
AddressDAO * aDAO = new AddressDAO (dao);
Address addr = aDAO->getByPrimaryKey(QVariant(1));
In my AddressDAO.cpp, I have:
template<class Address>
Address SpecializedDAO<Address>::getByPrimaryKey(const QVariant &key)
{ }
At link time, I get the following:
undefined reference to
`SpecializedDAO<Address>::getByPrimaryKey(QVariant const&)'
How would I correctly implement the methods in the SpecializedDAO class?
Update:
Stupid me, stupid me, stupid me.... I mostly got this to work. The issues....
My model classes (DTOs) are wrapped in namespaces and I use macros to define and use these namespaces. Plus, I tried to use a good hierarchy for these classes and found that moc has a reeeeal problem with class hierarchies wrapped in namespaces....
I fergot that function definitions of template classes need to be in the header file - can't be in separate compilation units.
qmake doesn't deal with (header file) dependencies very well when crossing library boundaries. I have my model stuff in a shared lib and the 'main()' function (in a separate directory) was trying to read a record from the DB. The 'main()' C file wasn't getting re-compiled when I changed my model class header file...
Here are more details:
In SpecializedDAO.h:
template<class DTO>
DTO SpecializedDAO<DTO>::getByPrimaryKey(const QVariant &key)
throw (FlowException)
{
DTO obj;
dao->getByPrimaryKey(static_cast<QObject &> (obj), key);
return obj;
}
In UniversalDAO.cpp:
void
UniversalDAO::getByPrimaryKey (QObject & dto, const QVariant & key)
{
<retrieve properties from 'dto' n build up QSqlQuery>
<execute QSqlQuery 'SELECT...' to retrieve record>
<call dto.setProperty() on all fields>
}
A current outstanding issue is use of user-defined types for property types in my DTO classes. I'm trying to use std::string vs. QString, but no matter what I tried (Q_DECLARE_METATYPE(std::string), qRegisterMetaType<std::string>(), etc., nothing seemed to work.... had to revert to Qt-based types. bummer....

Architecture of some reusable code

I am writing a number of small, simple applications which share a common structure and need to do some of the same things in the same ways (e.g. logging, database connection setup, environment setup) and I'm looking for some advice in structuring the reusable components. The code is written in a strongly and statically typed language (e.g. Java or C#, I've had to solve this problem in both). At the moment I've got this:
abstract class EmptyApp //this is the reusable bit
{
//various useful fields: loggers, db connections
abstract function body()
function run()
{
//do setup
this.body()
//do cleanup
}
}
class theApp extends EmptyApp //this is a given app
{
function body()
{
//do stuff using some fields from EmptyApp
}
function main()
{
theApp app = new theApp()
app.run()
}
}
Is there a better way? Perhaps as follows? I'm having trouble weighing the trade-offs...
abstract class EmptyApp
{
//various fields
}
class ReusableBits
{
static function doSetup(EmptyApp theApp)
static function doCleanup(EmptyApp theApp)
}
class theApp extends EmptyApp
{
function main()
{
ReusableBits.doSetup(this);
//do stuff using some fields from EmptyApp
ReusableBits.doCleanup(this);
}
}
One obvious tradeoff is that with option 2, the 'framework' can't wrap the app in a try-catch block...
I've always favored re-use through composition (your second option) rather than inheritance (your first option).
Inheritance should only be used when there is a relationship between the classes rather than for code reuse.
So for your example I would have multiple ReusableBits classes each doing 1 thing that each application a make use of as/when required.
This allows each application to re-use the parts of your framework that are relevant for that specific application without being forced to take everything, Allowing the individual applications more freedom. Re-use through inheritance can sometimes become very restrictive if you have some applications in the future that don't exactly fit into the structure you have in mind today.
You will also find unit testing and test driven development much easier if you break your framework up into separate utilities.
Why not make the framework call onto your customisable code ? So your client creates some object, and injects it into the framework. The framework initialises, calls setup() etc., and then calls your client's code. Upon completion (or even after a thrown exception), the framework then calls cleanup() and exits.
So your client would simply implement an interface such as (in Java)
public interface ClientCode {
void runClientStuff(); // for the sake of argument
}
and the framework code is configured with an implementation of this, and calls runClientStuff() whenever required.
So you don't derive from the application framework, but simply provide a class conforming to a particular contract. You can configure the application setup at runtime (e.g. what class the client will provide to the app) since you're not deriving from the app and so your dependency isn't static.
The above interface can be extended to have multiple methods, and the application can call the required methods at different stages in the lifecycle (e.g. to provide client-specific setup/cleanup) but that's an example of feature creep :-)
Remember, inheritance is only a good choice if all the object that are inheriting reuse the code duo to their similarities. or if you want callers to be able to interact with them in the same fission.
if what i just mentioned applies to you then based on my experience its always better to have the common logic in your base/abstract class.
this is how i would re-write your sample app in C#.
abstract class BaseClass
{
string field1 = "Hello World";
string field2 = "Goodbye World";
public void Start()
{
Console.WriteLine("Starting.");
Setup();
CustomWork();
Cleanup();
}
public virtual void Setup()
{Console.WriteLine("Doing Base Setup.");}
public virtual void Cleanup()
{Console.WriteLine("Doing Base Cleanup.");}
public abstract void CustomWork();
}
class MyClass : BaseClass
{
public override void CustomWork()
{Console.WriteLine("Doing Custome work.");}
public override void Cleanup()
{
Console.WriteLine("Doing Custom Cleanup");
//You can skip the next line if you want to replace the
//cleanup code rather than extending it
base.Cleanup();
}
}
void Main()
{
MyClass worker = new MyClass();
worker.Start();
}