How to convert an existing customized SwapChainPanel from C++/CX to C++/WinRT - c++-winrt

I'm attempting to convert my existing C++/CX code to C++/WinRT in order to figure out whether that would enable me to compile that code using Clang. However, I'm stuck early on.
The C++/CX code that I need to convert is used to build a Direct3D component (based on SwapChainPanel) that is eventually utilized in a Windows UWP app that is written in C#. The problem I'm facing is that I just don't manage to convert my customized SwapChainPanel to C++/WinRT.
The code looks as follows:
namespace Why::Does::This::Not::Work
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class BaseView : public Windows::UI::Xaml::Controls::SwapChainPanel
{
protected private:
BaseView();
// Lots of other stuff
};
}
namespace Why::Does::This::Not::Work
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class CustomView sealed : public BaseView
{
public:
CustomView();
// ...
event AnimationEventHandler^ AnimationStarted;
private protected:
// Lots of private protected stuff
};
}
namespace Why::Does::This::Not::Work
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class AnimationEventArgs sealed
{
public:
AnimationEventArgs() {}
AnimationEventArgs(int start, int end)
{
Start = start;
End = end;
}
property int Start;
property int End;
};
[Windows::Foundation::Metadata::WebHostHidden]
public delegate void AnimationEventHandler(Platform::Object^ sender, AnimationEventArgs^ e);
}
As far as I'm able to interpret the documentation I need to do what is described under If you're authoring a runtime class to be referenced in your XAML UI in the documentation.
So, it seems to me that I'd need to author an IDL file in order to generate the COM stuff that is required. However, I cannot even make the skeleton IDL compile:
namespace Why
{
namespace Does
{
namespace This
{
namespace Not
{
namespace Work
{
runtimeclass CustomView : Windows::UI::Xaml::Controls::SwapChainPanel
{
CustomView();
}
}
}
}
}
}
When attempting to compile the above code all I'm getting is
error MIDL2025: [msg]syntax error [context]: expecting { near ":"
error MIDL2026: [msg]cannot recover from earlier syntax errors; aborting compilation
I apologize if you view this as a stupid question. I have read the corresponding documentation but I just fail to comprehend what is really going on when utilizing C++/WinRT. I have plenty of experience with C++ but zero with COM which means it is everything else than straight forward to understand C++/WinRT.
If someone can lend me a hand translating the above C++/CX code to C++/WinRT that would be highly appreciated. Please don't just point me to the documentation, that just doesn't help.
EDIT:
Modifying the sample IDL code as follows successfully compiled it:
namespace Why
{
namespace Does
{
namespace This
{
namespace Not
{
namespace Work
{
[default_interface]
runtimeclass CustomView : Windows.UI.Xaml.Controls.SwapChainPanel
{
CustomView();
}
}
}
}
}
}
However, exposing a user control to another language, in my case C#, such as the one inheriting from SwapChainPanel is dramatically more complex than doing the same thing in C++/CX. There's an IDL to deal with that is not easy to handle because there don't seem to be any complex samples around. That IDL generates several header files that I'm not really sure about what to do with because the documentation is lacking and samples are sparse. C++/WinRT is not for the faint-hearted and its complexity compared to C++/CX is simpy much higher.
It seems to me that to really understand C++/WinRT it is a necessity to have a good grasp of COM because compared to C++/CX, C++/WinRT does a poor job of hiding those COM related internals. This is especially the case when dealing with DirectX. Add to this an IDL that in itself is hard to deal with and a documentation of it that might suffice to get simple samples up and running but does not help much when porting a full fledged C++/CX app.
Doing what we do with C++/CX in C++/WinRT is just not economical for and we will stay on C++/CX until C++/WinRT becomes much more user friendly. Eliminating the need for the IDL (see https://wpdev.uservoice.com/forums/110705-universal-windows-platform/suggestions/36095386-get-rid-of-idl-for-c-winrt-components) would help too.
Without the prospect of being able to compile our code using Clang I would not even think about moving away from C++/CX. Microsoft shouldn't wonder that the adoption of C++/WinRT is slow. If they seriously want to change that they have to lower the entry barrier considerably.

Fully qualified type names in IDL use the period (.) as the namespace separator. A working IDL file would look like this:
namespace Why
{
namespace Does
{
namespace This
{
namespace Not
{
namespace Work
{
runtimeclass CustomView : Windows.UI.Xaml.Controls.SwapChainPanel
{
CustomView();
}
}
}
}
}
}
There's fairly complete documentation at Microsoft Interface Definition Language 3.0 reference. Even with that, it's often challenging to make any sense out of MIDL error messages.

Related

Using Directx members between c++\CLI assemblies C3767

I am trying to call a member function from a C++/CLI assembly from another one, but when I start using DirectX struct I get C3767 error : candidate function not accessib
from Utilities.dll
#pragma once
#include "define.h"
namespace Utilities
{
public ref class Data
{
public:
BOOL CreateBuffer( LPDIRECT3DDEVICE9 dev)
{
...
return TRUE;
}
{
}
And using it from a renderer
#include "Renderer.h"
namespace SomeNamespace
{
SceneRenderer::SceneRenderer(void)
{
}
void SceneRenderer::Render(LPDIRECT3DDEVICE9 dev)
{
...
m_vbo->CreateBuffer(dev); //error C3767: 'Utilities::Data::CreateBuffer': candidate function(s) not accessible
...
}
}
I know that using the address of the device int* (&dev) I can cast back to a LPDIRECT3DDEVICE9, but im looking for a better solution
A managed C++ assembly will not export unmanaged types in its public interface by default. LPDIRECT3DDEVICE9 is an unmanaged type, so your CreateBuffer method will be marked private, regardless of the access specifier provided (kind of stupid that the compiller isn't even generating a warning about this).
Use #pragma make_public or, better yet, do not use unmanaged types in managed interfaces.
Suggestion: Use slimDx or Xna if you want to use DirectX in managed code. These libraries already provide managed wrappers for everything.

Disambiguating namespaces in generated XAML code

I have a Page that imports controls from a library like this:
<Page
x:Class="Foo.Bar.SomePage"
xmlns:myNamespace="using:Bar.Controls">
<myNamespace:SomeControl x:Name="someControl">
<!-- snip -->
</myNamespace:SomeControl>
</Page>
As you can see here, the page is declared in the ::Foo::Bar namespace, while SomeControl is declared in the ::Bar namespace. The problem I face is that Visual Studio generates this code:
namespace Bar {
namespace Controls {
ref class SomeControl;
}
}
namespace Foo
{
namespace Bar
{
partial ref class SomePage : /* ... */
{
/* ... */
private: Bar::SomeControl^ someControl;
};
}
}
The field definition Bar::SomeControl^ someControl tries to select ::Foo::Bar::SomeControl instead of ::Bar::SomeControl because Visual Studio doesn't fully-qualify it.
Is this by design (is there a way to phrase the using: URI in such a way that it will fully-qualify the name), or is this a bug? How can I work around that?
I think that I could convince people to make an exception to the namespace structure for this specific class, but it would be much simpler if there was an in-code solution for this.
For posterity, right now I'm using this kludge before #including the g.h file, but it's not super pretty:
namespace Foo
{
namespace Bar
{
typedef ::Bar::SomeControl SomeControl;
}
}
It introduces the control into the (incorrect) namespace so that it works even though the XAML code generator gets it wrong.

Can you apply aspects in PostSharp without using attributes?

I know with Castle Windsor, you can register aspects (when using method interception in Windsor as AOP) using code instead of applying attributes to classes. Is the same possible in Postsharp? It's a preference things, but prefer to have aspects matched to interfaces/objects in one place, as opposed to attributes all over.
Update:
Curious if I can assign aspects to interfaces/objects similiar to this:
container.Register(
Component
.For<IService>()
.ImplementedBy<Service>()
.Interceptors(InterceptorReference.ForType<LoggingAspect>()).Anywhere
);
If you could do this, you would have the option of NOT having to place attributes on assemblies/class/methods to apply aspects. I can then have one code file/class that contains which aspects are applied to which class/methods/etc.
Yes. You can either use multicasting (http://www.sharpcrafters.com/blog/post/Day-2-Applying-Aspects-with-Multicasting-Part-1.aspx , http://www.sharpcrafters.com/blog/post/Day-3-Applying-Aspects-with-Multicasting-Part-2.aspx) or you can use aspect providers (http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-12-e28093-Aspect-Providers-e28093-Part-1.aspx , http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-13-e28093-Aspect-Providers-e28093-Part-2.aspx).
Example:
using System;
using PostSharp.Aspects;
using PostSharp.Extensibility;
[assembly: PostSharpInterfaceTest.MyAspect(AttributeTargetTypes = "PostSharpInterfaceTest.Interface1", AttributeInheritance = MulticastInheritance.Multicast)]
namespace PostSharpInterfaceTest
{
class Program
{
static void Main(string[] args)
{
Example e = new Example();
Example2 e2 = new Example2();
e.DoSomething();
e2.DoSomething();
Console.ReadKey();
}
}
class Example : Interface1
{
public void DoSomething()
{
Console.WriteLine("Doing something");
}
}
class Example2 : Interface1
{
public void DoSomething()
{
Console.WriteLine("Doing something else");
}
}
interface Interface1
{
void DoSomething();
}
[Serializable]
class MyAspect : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine("Entered " + args.Method.Name);
}
}
}
I recommend that if you have complex requirements for determining which types get certain aspects that you consider creating an aspect provider instead.
Have a look at LOOM.NET, there you have a post compiler and a runtime weaver. With the later one you are able to archive exactly what you want.
It should be possible to use the PostSharp XML configuration. The XML configuration is the unification of the Plug-in and Project models in the project loader.
Description of .psproj could be found at http://www.sharpcrafters.com/blog/post/Configuring-PostSharp-Diagnostics-Toolkits.aspx.
Note, that I've only seen examples how PostSharp Toolkits use this XML configuration.
But it should work for custom aspects the same way.
Warning: I've noticed that installation of a PostSharp Toolkit from Nuget overwrites existing psproj file. So do not forget to back up it.

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....

Internal references in a VS2005.NET project

I have a C++/CLI class library project in VS2005 that i am having some problems with. I have defined a class called Languages which is a an enum class. which looks like this:
"Language.cpp"
namespace Company
{
namespace product
{
public eunm class Languages : int
{
English = 1,
German = 2,
//etc for other languages
};
}
};
I then have another class that tries to references this which lives in the same namespace:
"Language.cpp"
namespace Company
{
namespace product
{
public class LanguageConsumer
{
public:
LanguageConsumer()
{
}
public:
Languages DoSomething(Languages input)
{
if (input == Languages::English)
{
//Do something and return
}
};
}
};
However my project doensn't compile. From what i can figure out the different classes can't see each other even thought they are in the same namespace. I assume that i might need to have header files and #includes for the header files but i just don't know enough about C++/CLI to be sure (i come from C# background with hardly any C experience) and i have tried as many different combinations as i can think of. I'm sure i'm missing something very obvious to anybody who knows what they are doing, but alas i do not.
Thanks in advance.
C++/CLI still compiles like C++, file files are compiled separately and then linked together. This is different from C# which compiles all the files together. At compile time the files don't know about each other so the code doesn't compile (what is this enum?!). You need to have the enum definition in the same file (compilation unit) as the class.
The simple way to do this is to move the code into the same file. The header file solution is to move the enum definition into a header file and then include it (#include) in the other file. #include inserts the text of another file, giving the same effect.