Can I use WRL to write a COM server? - c++

Can I use the WRL library in C++ as a replacement for ATL to write a COM component? And if yes, would I be able to use it on older desktop Windows systems, like Windows XP?
I'm pretty sure that the answer to the first question is positive as I found this tutorial on MSDN:
http://msdn.microsoft.com/en-us/library/jj822931.aspx
but what about non-Windows 8 systems?

Well, sure you can. You can write a COM server in pure C++ code without any helper classes at all. You can write one in C if you really want to, although that's a violation of the Geneva Convention on Programmer's Rights in most jurisdictions.
What is probably not so visible is what is missing. WRL just doesn't make it any easier to write a server. Or maintain it. What you'll miss out on:
No help whatsoever to implement IDispatch. Obsoleted in WinRT but still quite important in regular servers. The only way to consume the server from a scripting language, IDispatch provides the late binding support.
No help whatsoever for registration. Obsoleted in WinRT, required for regular servers. Note how the DllRegisterServer() entrypoint is missing. The page you linked patches around the problem by requiring you to write a registry script by hand. That works, it is not exactly something you'd want to maintain or document so IT staff can get it right.
No wrappers for Automation types like BSTR, VARIANT and SAFEARRAY. Obsoleted in WinRT along with IDispatch. You can still fall back to <comutil.h> however.
No help whatsoever from the wizards that are built into Visual Studio that help you get it right. COM servers are awkward because definitions appear in multiple places in your code. And need to be an exact match. You get no help to ensure that CalculatorComponent is an exact match with the IDL, it is entirely up to you. Compiler errors you get from making small mistakes, particularly when maintaining it, can be painful.
And a whole bunch if smaller stuff not worth mentioning, like apartments, ActiveX, aggregation, error info, etc. Hurts pretty bad when you need it though. A possible advantage of WRL is that there's less mystical glue, ATL has a fair amount of it that considerably raises the abstraction level. That was intentional but it has to be learned. There's none at all when you use pure C++ of course, albeit that you have to write too much of it yourself.

Yes. You can write a standard COM component.
There is a sample for this directly in the docs.
And no: Such a COM component will only run on Windows 8 and later...

Related

How to write a DirectX audio push source

I want to create a DirectX 'filter' that sources a single channel of audio. I have seen the Platform SDK sample projects, but the downside there is that those require the ATL library.
Is there a way to create DirectX filters without resorting to ATL or MFC? I.e., some way using only gcc (e.g., MinGW) and other actually free tools?
If I understand right, the filter has to be a COM component. You can, sort of, write those from most compilers, if need be.
However, the boilerplate that would involve would be incredible, I had a 18kloc codebase that turned into 25kloc when turned into COM components (ended up turning it back just because there was more boilerplate COM than actual code for small plugins).
MFC isn't necessary or always involved in writing COM components, that I know of.
ATL helps simplify that greatly, by providing templates and functions to handle a lot of the details at compile-time. You may be able to use it from GCC, but I'm not sure what would happen; I doubt it would work well, though it might work.
Without ATL, you need MIDL and to generate the code from there. That is possible with free tools, it's done in a few places in the Wine project; you may check the code and toolchains there.
No matter where you do it, it'll be a pain, and a serious pain if you insist on using "actually free" tools for it (as they're not particularly designed to work with COM).
If you had DirectShow filter in mind, the best starting point would be PushSource Windows SDK Sample, which generates video and making it generate audio.
Also note that DirectShow bases classes are one of the earliest COM bases and they do not use ATL/MFC. The base classses themselves are also included with Windows SDK.

What's the fundamental difference between MFC and ATL?

Assuming I am only using them for "normal" GUI programs (no COM, no ActiveX, nothing fancy), what is the fundamental difference I will see between ATL and MFC, to help me figure out which one to use?
I've done some searches on the web, but ultimately none of the answers really answered my question:
http://msdn.microsoft.com/en-us/library/bk8ytxz5(v=vs.80).aspx:
"ATL is a fast, easy way to both create a COM component in C++ and maintain a small footprint. Use ATL to create a control if you don't need all of the built-in functionality that MFC automatically provides."
Doesn't really answer my question, because:
I'm not working with COM.
Does this imply MFC isn't fast? Why/how?
"MFC allows you to create full applications, ActiveX controls, and active documents. If you have already created a control with MFC, you may want to continue development in MFC. When creating a new control, consider using ATL if you don't need all of MFC's built-in functionality."
Also doesn't answer my question, because:
I don't really even know what ActiveX is in the first place.
It looks as though Microsoft is discouraging the use of MFC, but I can't figure out why.
What exactly is MFC's "built-in functionality" that ATL doesn't provide?
In general, this doesn't answer my question because it doesn't explain the downsides and the reasons behind them.
because directly or indirectly, everything seems to link back to the previous page:
How do I decide whether to use ATL, MFC, Win32 or CLR for a new C++ project?
"ATL & MFC are somewhat trickier to decide between. [[No kidding!]] I'd refer you to MSDN's page for choosing in order to decide between them."
Obviously, this doesn't answer my question. :)
http://www.codeguru.com/forum/archive/index.php/t-64778.html
etc.
What I have currently observed (within the last couple of days, while trying to learn both):
ATL is based on templates, or compile-time polymorphism.
ATL methods tend to be non-virtual, and tend to return references.
MFC is based on virtual methods, or run-time polymorphism.
MFC methods tend to be virtual, and tend to return pointers.
But there doesn't seem to be any architectural difference between them:
Both use message maps (BEGIN_MSG_MAP vs. BEGIN_MESSAGE_MAP... big deal)
Both wrap Win32 methods into classes
Both seem to have similar classes CWnd vs. CWindow
But then, if there's no real difference except for the compile-time vs. run-time aspect, then why do both of them exist? Shouldn't one of them be enough?
What am I missing here?
I think the answer to your question is mostly historical, if you look back at how the two libraries originated and evolved through time.
The short answer is, if you are not doing anything "fancy", use ATL. It's great for simple user interfaces with COM thrown in.
The long answer:
MFC was built in the early 90s to try out this new language called C++ and apply it to Windows. It made Office like features available to the development community when the OS didn't have them yet.
[Edit embellishment: I did not work at Microsoft, so I don't know if Office was ever built on MFC, but I think the answer is no. Back in Win 3.1, Win 95 days, Office UI team would invent new controls, package them up in libraries, then the Windows and MFC teams would incorporate wrappers and API to those controls with redistributable dlls. I would guess there was a bit of collaboration and code sharing between those teams. Eventually those controls would make it into the base operating system in service packs or the next Windows version. This pattern continued with the Office Ribbon which was added into Windows as an add-on component well after Office shipped, and is now part of the Windows OS.]
At that time the library was quite primitive, both because of the C++ language and compiler being new, and Microsoft building it up over time as Office evolved.
Because of this history, MFC:
Has a fairly clunky design. It started as a light wrapper around the Windows API, but grew. There are a bunch of little 'features' that had to be invented because the compiler and language just didn't support them. There were no templates, they invented a string class, they invented list classes, they designed their own run time type identification, etc.
Encapsulates 20 years of Office and Windows evolution, which includes a whole crap load of stuff you will probably never use: Single and Multiple Document interfaces, DDE, COM, COM+, DCOM, Document Linking and Embedding (so you can embed a word document in your app if you wanted to), ActiveX controls (evolution of object embedding for the web!), Structured Document Storage, Serialization and Versioning, Automation (from early VBA years), and of course MVC. The latest versions have support for Visual Studio style window docking, and the Office ribbon. Basically every technology out of Redmond in 20 years is in there somewhere. It's just HUGE!
Has a ton of little gotchas, bugs, workarounds, assumptions, support for things that are still there that you will never use, and they cause problems. You need to be intimately familiar with the implementation of many classes and how they interact to use it on a decent size project. Delving into MFC source code during debugging is common. Finding a 15 year old tech note on some pointer being null causing a crash still happens. Assumptions on initialization of ancient document embedding stuff can affect your application in weird ways. There's no such thing as abstraction in MFC, you need to work with it's quirks and internals daily, it doesn't hide anything. And don't get me started on the class wizard.
ATL was invented as the C++ language evolved, and templates arrived. ATL was a showcase of how to use templates to avoid the run-time problems of the MFC library:
Message maps: Since they are template based, types are checked, and if you screw up the bound function, it doesn't build. In MFC message maps are macro based, and run-time bound. This can cause odd bugs, message routed to the wrong window, a crash if you have function or macro defined incorrectly, or just simply not work because something isn't hooked up right. Much more difficult to debug, and easier to break without noticing.
COM/Automation: Similar to message maps, COM was originally run-time bound using Macros, requiring lots of error handing and causing odd problems. ATL made it template based, compile time bound, and much, much easier to deal with.
[Edit Embellishment: At the time ATL was created, Microsoft's technical road map was mainly focused on 'Document Management'. Apple was killing them in the desktop publishing business. Office 'Document Linking and Embedding' was a main component to enhancing the 'Document Management' features of Office to compete in this space. COM was a core technology invented for application integration, and Document Embedding API's were based on COM. MFC was difficult to use for this use case. ATL was a good solution to make this particular technology easier for 3rd party's to implement COM and utilize document embedding features.]
These little improvements make ATL hugely easier to deal with on a simple application that doesn't need all the office like features of MFC. Something with a simple UI and some Office automation thrown in. It's small, it's fast, it's compile time bound saving you much time and headache. MFC has a huge library of classes that can be clunky, and difficult to work with.
Unfortunately ATL stagnated. It had wrappers for the windows API and COM support, and then it never really went beyond that. When the Web took off, all this stuff was sort of forgotten as old news.
[Edit Embellishment: Microsoft realized that this 'Internet Thing' was going to be big. Their technical road map changed drastically to focus on Internet Explorer, Windows Server, IIS, ASP, SQL Server, COM/DCOM in Distributed Transaction Server. So the Document Linking and Embedding was no longer a high priority.]
The huge footprint of MFC made it impossible for them to dump, so it still evolves slowly. Templates have been incorporated back into the library, as well as other language and API enhancements. (I had not heard of WTL until I saw this question. :)
Ultimately, which one to use is simply a matter of preference. The majority of the features you need are in the base OS API, which you can call directly from either library, if there is no suitable wrapper in the library.
Just my 2 cents based on using MFC for many years, and I use it now daily. I dabbled in ATL when it was first released on a few projects for a couple of years. It was a breath of fresh air in those days, but never really went anywhere. And then the Web came along and I forgot all about it.
Edit: This answer has surprising longevity. Since it keeps popping up in my stack overflow page, I thought I'd add some embellishment to the original answer I thought was lacking.
I have been told by many people who have used both that their programming experience was less painful with ATL than with MFC. Your compiled executable will also be much smaller with ATL.
I recommend you take a look at WTL, as it builds upon ATL.
What is that "extra functionality" they keep mentioning? Do I need it?
If you define your requirements, it might be easier to answer if you can avoid using MFC. Unfortunately "nothing fancy" isn't exclusive enough. Being inclusive as to which features you intend to use might be more helpful (which controls, which frameworks/technologies/existing libraries you want to use, etc).
But here's an article that describes some features in MFC that aren't directly supported by WTL/ATL.
MFC also has evolved to the point it supports a great many desirable features, such as MAPI, support for the other Windows logo requirements, sockets, documents (if you like and/or use that pattern), and compound document files. WTL has its share of cool features, but MFC is the clear feature champ. Both environments support framed main window architectures (frame window with separate view window), SDI and MDI applications, split windows, dialog-based applications, and various COM-based classes for COM support.
ATL is a set of classes meant to simplify the implementation of COM objects.
You can use it without MFC. At my job, we use ATL to expose COM interfaces to computational code. There is no GUI involved, it is for us to be able to call this computational code from eg. Excel VBA.
Look at some COM guide/tutorial to see what it abstracts.
MFC is just a set of GUI wrapper classes to the Win32 API. Look at some Win32 API tutorial to see what it abstracts.

C++ developing a GUI - classes?

I do have to say I'm fairly inexperienced when it comes to C++, don't be too harsh on me.
Recently stumbled unto the wonders of the win32 API and have chosen to practice using it (I'd rather not use MFC/wxWidgets/etc at this point, just for educational purposes).
Well, my real question is:
How do you properly code your win32 GUI stuff into classes. I mean, sure, you can make a class that saves individual window handles, allows for easier modification of window properties, has a more simplified version of CreateWindow(). But as I understand it you will need a messagepump and several callback functions for your created windows. How does that work when combining them with classes?
Could anyone point me in the right direction here? I don't mind reading (a lot of) example code as long as it is commented.
PS: I'm also having trouble finding good (read: easy) documentation on using 'resource files' for my window decorations. Bonuspoints for that! :)
I program in C++ for a living. I like C++.
That said, your life will be so much easier if you do your windows GUI in something .Net, e.g., C#. Win32 is very low-level and you will be building tons of stuff that you will get for free with the .Net libraries. Win32 is not a wonder, anymore. :-)
If you want to learn C++, pick something other than a GUI to do with it.
I personally would use MFC instead of reinventing the wheel here. However, if you insist you need to have an application object that is instantiated when the program is run and contains the message loop and a mechanism for forwarding messages to the correct window objects.
That's the way MFC does it, at least. I'm not sure if the MFC source code is available for download, but if you have access to Visual C++ install disks (any version) you should be able to install the source code on your computer to review.
The biggest problem I faced back when I used the Win32 API (have since moved on to Linux and cross-platform solutions) were the callbacks. Especially the winproc one, AKA the message pump. I found this, which should be a good hint. I did what that page suggests when I rolled my own wrapper.
Look at MFC or ATL/WFC. If you want to re-invent the wheel, the best reference source for how to do so is the wheel itself, especially since the source code is readily available.
I would suggest reading Windows++ by Paul Dilascia. It takes you through the whole process of building a class library in C++ on top of the Windows API. It's written for 16-bit Windows, but all of the concepts presented in the book still apply. Plus, you can get it really cheap since it's "out of date".
And make sure you learn about message crackers (#include <windowsx.h>), they will keep you from pulling out too much hair. ;-)
The best way to learn this is to go and readCharles Petzold's original book. He does a good job of showing how to set up the base message loop and how to build statements for routing the various events to handlers. The real problem here is that by reinventing everything you are going to be spending hours and hours writing and debugging windows event hanlding code instead of writing your own application.
Unless you have a compelling reason for doing this yourself, you woudl be far better served using someone else's construct like MFC.
The only reason I see for coding all this yourself is if you want a basic understanding of how it works before you switch over to MFC or something similar. At least this way you would see how it works under the covers before you can forget it forever.
Many years ago, I developed a set of classes to encapsulate the API (various reasons why we couldn't use MFC). I learned a lot from the MFC source code.
The big key is that every window has a UserInfo data member - you can use it for whatever you want. What you'll want to use it for is the class's this pointer.
Now, the other tricky thing is that the message handler callback function cannot be a normal class member function, as Windows uses C calls and not C++. So your callbacks must be statics. However, since you've saved the class's this pointer, its just a matter of getting the class's userinfo, casting it to your class's this pointer and then calling whatever (non-static) class functions you need.
If you plan it correctly, inheritance will work well, including all of the inheritance that the windows themselves exhibit (ie, an Edit is a Control is a Window).
The only reason I would recommend not reinventing the wheel is you are neither an expert at C++ nor the Win32 API. Trying to learn two unrelated subjects at once will not be productive. If you want to become better at C++, write a library for a subject you know a lot about. If you want to learn the Win32 API, program it raw to understand how it works before creating (or using) a wrapper for it.
There is a pretty good C++ Windows API tutorial on the Reliable Software site.

How to add a simple API to my C++ application for access by LabView?

I have a data acquisition program written in C++ (Visual Studio 6.0). Some clients would like to control the software from their own custom software or LabView. I would like to come up with a simple API with a dll I can distribute to them and would like some tips on how to get started. This is going to be VERY basic, maybe 4 or 5 commands. My DAQ program will still be running in its own window on the same machine, I would just like to set it up to be controlled from another program.
You are on the right track with a DLL. The real trick, it sounds like, will be deciding what sort of inter-process communication (IPC) you want to use. Options are: sockets, pipes, shared memory, synchronization objects (events, etc.), files, registry, etc.
Once you decide that, then implement a listener within your executable to wait for incoming IPC messages from whatever software is using your DLL.
As far as the API is concerned, you can keep it simple just like you were wanting. Have the DLL expose your 4 or 5 functions (make sure you only use native data types, like char* and long, to avoid module boundary issues), and then those will use your IPC mechanism to communicate with your executing app.
Things that start simple like this have a habit of growing over time, so you may be better off doing a little more work up front and using a technique that will grow with you.
Implementing a COM interface to your program would give the clients are lot of freedom in how the interface with it, and you wouldn't have to worry about the mechanics of IPC, etc since COM is designed to hide all that from you.
In the future COM already has well define idioms for things like events that are well support by scripting languages, etc should you need them.
Update: there are a lot of ways of implementing COM. You can build it from the first principals with the guide of a good COM book, or use of framework like ATL to save some of the boiler plate. There are a lot of good samples, for example see MSDN.
The big advantage of COM is that you don't need a DLL! Your application would always be running, you say. That means that it can act as the COM object creator ("local server").
If someone would want a "stdcall" DLL instead, you could give them a DLL that internally just forwards all calls to the COM interface. Writing it would be quite trivial. You only have 5 functions, you say. That suggests you have one COM interface, with those 5 methods. When the wrapper DLL loads, it asks your EXE to create its COM object. The DLL in turn exposes 5 stdcall methods, each of which calls one method on the COM object.
You could use a dll. I'd consider it. But I'd also consider whipping up a simple http-based API, preferably RESTful.
Advantages: Easy to port. Can write a client app from any language trivially. Can work across a network. Testing becomes easier (use a scripting language or your browser).
Disadvantages: Performance is going to be slower. Significantly more plumbing to set it up in C++. I'm not sure if LabView can make http calls.
Something like:
http://xxx/data [GET, maybe POST for testing]
http://xxx/data/start [POST]
http://xxx/data/stop [POST]
http://xxx/data/parameters [POST]
Given your requirements it may be slightly overkill but then maybe not. Many apps I've worked on have had to be ported and would have been quicker to extend if we could have used a faster dev language to test and extend it.
LabVIEW supports making DLL calls, but this is one of the weaker spots in LabVIEW development. Done incorrectly, this can lead to an application that is more prone to crashes. As a LabVIEW developer, I like MattyT's suggestion of creating an HTTP service. Every language on every platform that can make a TCP/IP port can access it then. I think you could use your own custom TCP/IP protocol instead of full bore HTTP, but either way the compatability issue is solved.
If you do use DLLs, here are some tips. Don't use structs or pointers to structs in your function call argument list. Don't allocate memory in the DLL to be passed back to LabVIEW. LabVIEW has built in memmory management and won't play well with others. This may apply to other languages that have memory management such as Java. LabVIEW will work better if it allocates the memory and passes a pointer to the DLL. Avoid pointers, arrays and strings where possible. LabVIEW can pass these to DLLs, but it is an advanced topic and works best when the LabVIEW developer also knows C, which will not always be the case.
There is a related question here. I don't want to end up with something that is LabView-specific, and it appears that LabView can access dlls if they use stdcall. A dll like this would be callable from a VB or other Windows software as well which is what I'm shooting for.
I'm not sure about it's ability to access a COM interface but would appreciate some more detail on what that would look like for my application.

What kind of code library should I build for distribution?

I need to build a C++ library to distribute among our customers. The library must be able to be accessed from a wide range of languages including VB6, C++, VB.net and C#.
I've being using ActiveX controls (ocx files) until now. But I wonder if there is a better kind of library (dll, etc.) that I can build. What do you recommend?
I'm limited to C++ as the library language, but you can mention other languages for reference to other developers.
P.S. Sorry if the question was already asked. I had some trouble finding a suitable title. Feel free to correct my English.
Edit: Seems like the best choice is either DLLs or OCX (i.e., COM), but I'm still having some doubts on which one will I choose. Which one is more suitable to modern languages (.NET for instance)? Which one would be easier to use from an end developer perspective?
Almost every language has a way of loading dynamic libraries and accessing exported C functions from them.
There is nothing preventing you from using C++ inside the dll but for maximum portability, export only C functions.
I have some more about this in this post.
If you're looking at supporting both VB6 and .NET, you're pretty much stuck with exposing interfaces via COM, but at least that'll get you out of having to create more than one wrapper based on the language/runtime system you're trying to interact with.
If there is any chance this will need to be ported to non windows platforms then a DLL / Shared library is your best choice as a COM object really isn't at all portable.
In addition you can call a DLL from almost any platform even if it requires you to write a wrapper of some kind. It's pretty easy to wrap a dll in a com object but if you make a native com object it's a lot harder to add a C style DLL API. Plus you might want to call it from java for example and it's much easier to write a JNI wrapper to call your DLL than get it working with COM in any kind of cross platform way.
Really it depends on what platforms you really need to call it from and how certain you can be that you won't get something out of the ordinary in future.
To be callable from all those languages your only real option is going to be COM, without having to write wrappers where required (which would defeat the point)