Simplest way to implement .NET events for C++ - c#

I have a .NET library, that needs to be exposed for COM interop, including some asynchronous operations. As such, I need to implement events. Implementing events from C# seems easy as:
[ComVisible(true)]
[Guid("...")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IClass1Event))]
public class Class1: IClass1
{
public delegate Int32 IntIntFunc(Int32 arg);
public event IntIntFunc Event;
public Int32 RaiseEvent(Int32 param)
{...}
}
[ComVisible(true)]
[Guid("...")]
public interface IClass1
{
Int32 RaiseEvent(Int32 param);
}
[ComVisible(true)]
[Guid("...")]
public interface IClass1Event
{
Int32 Event(Int32 param);
}
But I have trouble implementing a C++ event sink.
Various examples I've come across range from plain IConnectionPoint::Advise to mere "use VB", but I come across every kind of problem trying to implement them (and no, I can not use VB) - either ATL refuses to implement AddRef for me, or I can not grasp VTables with my mind (I am very basically versed in C frameworks, unfortunately).
I have no information on what framework is preferable, only that client is C++.
So my question is: what'd be the leanest way to expose .NET events to C++, and consequently, what'd be the simplest way to implement a test sink?
P.S.: Do I really need an events interface to be IDispatch?

C++ vtables are very easy, if you're familiar with COM. Microsoft pretty much defined them to be identical. That's to say, the MSVC++ vtable for class IUnknown is binary the same as the COM function table of interface IUnknown.
Now, you seem to stumble on IConnectionPoint::Advise. That's understandable. It looks like an interface that you must implement, but it isn't. It's an interface implemented by the event source. You use it to tell the source what sink to use.
To see what happens, pass a dummy IUnknown object to IConnectionPoint::Advise and put a breakpoint on your IUnknown::QueryInterface. You'll see the event source query for IClass1Event, by GUID of course. Now, when you implement that, you can return it from IUnknown::QueryInterface.
You don't need to implement an IDispatch interface. .Net can do without; it's the old Visual Basic 6 which needs it. That's because VB6 is weakly typed and needs late binding.
More reading material.

Related

C# COM visible type: is GUID needed?

I have the following class:
[ComVisible(true)]
[Guid("F8351C66-7F0E-4E38-AE64-9A262202E230")]
[ProgId("CarProject.CarFactory")]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class CarFactory
{
public CarFactory()
{}
[DispId(0)]
public Car CreateCar(int tyres)
{
return new Car(tyres);
}
}
[ComVisible(true)]
[Guid("83f622b9-74f4-4700-9167-52c4ce9e79aa")]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class Car
{
[DispId(0)]
public int NumberOfTyres { get; private set; }
public Car(int tyres)
{
this.NumberOfTyres = tyres;
}
}
The Car object is created by a factory therefore the COM client uses only the _Car interface autogenerated. Note that there isn't a default constructor so the class cannot be instantiated through COM.
My question is: is the Guid attribute needed? I cannot find its value in the registry.
No, it is not needed since it will never be used. In fact, it is never needed and applying [Guid] is a pretty bad practice.
There are several other problems with this declaration style, discussing them all requires me to write a book and that is not very practical. It will be a lot easier for you to look at the decompiled type library so you can see what the client compiler sees. Use the Visual Studio Developer Command prompt, generates the type library if you don't have one yet with Tlbexp.exe. Run Oleview.exe, File > View Typelib and select the .tlb file. Highlighting the relevant details you now see:
importlib("mscorlib.tlb");
This is pretty awkward, the client programmer doesn't just have to add a reference to your type library but also the .NET type library for mscorlib.dll. Stored in the c:\windows\microsoft.net\framework\v4.0.30319 directory. Or v2.0.50727, the older version. Pretty unintuitive and does not often come to a good end. Note how you got in trouble with it in your previous question. Read on to find out why this happened.
[
odl,
uuid(BD7A2C0E-E561-3EBC-8BB7-1C72EE61D5B0),
hidden,
dual,
nonextensible,
oleautomation,
custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "ClassLibrary171.Car")
]
interface _Car : IDispatch {
// etc..
}
This is the auto-generated "class interface", you already now about it. This is the one that the client compiler actually uses to make calls. Note the [uuid] attribute, same as the [Guid] attribute in C#. But it has a pretty random value. It was auto-generated, like the interface was. So using [Guid] in your declaration did not actually accomplish anything at all.
The [hidden] attribute as well as the leading underscore on the interface name tell an type browser tool (like Object Browser in VS) to hide the declaration. Made it important to use OleView to see the details. Otherwise a quirk that goes back to the kind of languages that don't have support for interfaces, old versions of Visual Basic (like VB6 and VBA) and scripting languages (like VBScript and JavaScript) being the primary examples. Such languages need to emulate them by making the interface look like a class, the only reason why you'd consider exposing the class at all.
[
uuid(83F622B9-74F4-4700-9167-52C4CE9E79AA),
version(1.0),
noncreatable,
custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "ClassLibrary171.Car")
]
coclass Car {
[default] interface _Car;
interface _Object;
};
Note the [noncreatable] attribute. The type library exporter could see that client code can never create a Car instance since it has no default constructor. That in turn helps Regasm.exe figure out that registering the CLSID for Car is not necessary, that's why you could not find it back in the registry.
And note the _Object interface. Appeared because every .NET class derives from System.Object. And, likewise, the _Car interface also has the methods of Object (ToString, Equals, GetHashCode, GetType) since Car inherited them. This is how you ended up with the dependency on mscorlib.tlb. They might be useful to the client programmer, but that is not common and you generally certainly don't want to have to document them. The less you expose, the better.
Long story short, this happened because you used ClassInterfaceType.AutoDual. It is a convenience, but not a very good one and Microsoft strongly discourages it, recommending ClassInterfaceType.AutoDispatch instead. But that's only useful for scripting languages.
You avoid all this by declaring the ICar interface explicitly instead of letting the type library exporter generate it for you. It needs to be [ComVisible(true)] and the class needs to implement it. Now you can use ClassInterfaceType.None.
And now you can give the interface a [Guid]. But beware the bad practice this is, COM demands that interfaces are immutable. Once you exposed one in the wild, you can never change it again. Very important, COM has a nasty DLL Hell problem, caused by registration being machine-wide and you in general have no guarantee whatsoever that you can get the client programs recompiled. The crashes this can cause a very hard to diagnose. If you do have to change it then the interface needs a new [Guid] so both the old and the new interface can co-exist. Most trivially done by simply omitting the attribute entirely, the CLR already auto-generates it. Using [Guid] does allow creating interfaces that are binary compatible with an old interface declaration, but that's pretty hard to do correctly.

Where do I put DispID when a interace implements a interface for COM Interop

I'm not 100% positive in my code that I'm doing this right. Basically I'm making a managed COM object/library in C#. I'm doing it this way so that if someone uses my SDK they are not bound to use .NET. After reading a bunch of articles I found out that I have to make a interface for my events if my main class is going to have events. MSDN Article I read that from so I made my interface like so.
[ComVisible(true),
Guid("A34160EA-xxxx-xxxx-xxxx-xxxxxxxxxxxx"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IBarcodeEvents
{
//should dispid be here?
void BarcodeDataReceived(Interfaces.IBPBarcodeDevice device);
}
Then I read that VB6 really needs/wants to have a DispID attribute. (A unique one per com object) but I'm confused. Do I put the DispId in my IBarcodeEvents or in IBPBarcodeDevice (comments removed for brevity)
[Guid("96CB4F45-xxxx-xxxx-xxxx-xxxxxxxxxxxx"), ComVisible(true)]
public interface IBPBarcodeDevice : IBarcodeEvents
{
[DispId(5001)]
Data.BarcodeData GetBarcodeData();
[DispId(5002)]
bool HasBarcodeData();
[DispId(5003)]
void EnableBarcodeScanner();
[DispId(5004)]
void DisableBarcodeScaner();
[DispId(5101)]
event BarcodeDataReceivedHandler BarcodeDataReceived;
}
Sure, the members of an IDispatch interface require a dispid to make late binding work. It is what powers the IDispatch::Invoke() function. It is so important that the type library exporter will auto-generate them if you omit the [DispId] attributes. Which by itself already does a fine job. As long as you pick arbitrary numbers like 5001 then there is no point in avoiding the auto-generated ones. It will not work "better".
public interface IBPBarcodeDevice : IBarcodeEvents
This is not correct, the events interface must be separate from the interfaces that expose methods like EnableBarcodeScanner(). An event interface only appears in your [ComSourceInterfaces] attribute and nowhere else. It is the job of the event listener to implement it, not the event source. The listener is the one that gets the callbacks on its BarcodeDataReceived() method. Or to put it another way, you don't listen to your own events, only the client code is interested in them and it must therefore implement IBarcodeEvents. It must not implement IBPBarcodeDevice.
Review the MSDN example, note how the Button class does not implement the ButtonEvents interface. The binding between the event you declare in your class and the interface methods that the client implements is part of the standard COM plumbing that any language runtime implements.
Which answers your question, you apply the attributes to the IBarcodeEvents methods. But since the actual values never matter for event interface methods you can simply omit them.

Automatic (and not refactor-related) extraction of interface from class

I'm relatively new to C# so this may be a somewhat naive question.
Does there exist a way, or can one even be constructed, to construct an interface containing all the public methods/properties of a class?
I find myself in a project using the mocking framework Moq. Moq has an apparently rather common limitation in that it can only handle interfaces and virtual methods. The project's architect has decided to go the interface route, which means every class in the project has an accompanying interface. This means there are loads of interfaces implemented by a single class. Furthermore, the style mandates that interfaces go into their own files. This means there are loads of files in the project.
In my opinion it would be a real improvement if these interface-and-files-just-for-Moq could be a bit less intrusive. Is there no way to have the system (Visual Studio/.Net/C#) create them.
For instance, if writing this
[ExtractAndImplement("IFoo")]
public class Foo
{
public int Bar(int baz)
{
...
}
}
would be equivalent to
public interface IFoo
{
int Bar(int baz);
}
public class Foo : IFoo
{
public int Bar(int baz)
{
...
}
}
NB No, Refactor -> Extract Interface does not do what I want. First off, it creates an interface in source code somewhere, so it doesn't reduce the clutter of singly-implemented interfaces. Second, it's an interface I need to maintain explicitly; when I add a public method in the class I need to extract that new method to the correct interface. No, I'd like to have something that's implicit, i.e. interfaces are created on the fly without cluttering the source or the project.
I'm guessing that in Lisp/Scheme it'd be done using macros, and in Haskell using templates.
You can do this in Visual Studio (not in the express version).
Use Refactor -> Extract Interface. The cursor needs to be placed on the classname.
For more information:
http://msdn.microsoft.com/en-us/library/fb3dyx26.aspx
You could also look at ReSharper for this option or SharpDevelop.
You are probably asking for
The interface language is in Italian (It says "Extract Interface"), sorry, but you got a hint I hope.

Pass C# interfaces/classes to F#

I have an existing project written in C#. I would like to move part of its business logic to F#.
MyObjectX is a C# class that runs scientific algorithms.
For MyObjectX to run it needs to implement a couple of interfaces, and some dependencies that are injected via methods (not constructor). Example:
public class MyObjectX(): IMathSolver, IBusinessSolver
{
//private fields
private int operationMode;
private ISignalProvider signal;
//Inject dependcy via method
public void SetSignalProvider(ISignalProvider signal)
{
this.signal = signal;
}
//implemention of above interfaces
public double MethodMathSolver()
{
this.signal.GetThreshold();
//...
}
public double Method1BusinessSolver()
{
}
public double Method2MathSolver(IResultProvider provider)
{
var x = provider.GetValueAtTime(0.1);
//...
}
}
So now I would like to implement MyObjectX in F#. What is the best way to do that so i can be as functional as possible in my code?
Make the existing C# MyObjectX behave as a wrapper/facade between the rest of C# classes and the F# library were the algorithms are implemented in F# modules.
Write a F# class of MyObjectX class that implements the interfaces, and probably call other F# modules.
Or non of them. please advise.
Also what is the best way to pass the dependencies of C# to F# like 'IResultProvider/ISignalProvider'? Do i need to use mutable variables that will get populated with the dependencies via functions in F#?
Please advise. if you can share a code sample i would be thankful.
I think you could choose between 1 and 2. These are certainly the two most reasonable approaches.
I think that the option 2 might be better, because the F# implementation can then stay in simple F# modules using the most idiomatic F# style (such as passing functions around as arguments). The idiomatic F# code is not always easy to use from C#, so if you wrap it in an F# class that implements the required C# interfaces, you are hiding the "F# details" from the C# code, which is good.
Have a look at:
F# Component Design Guidelines which says more things about how to design F# components in a way that makes them easy to use from C#.
Interfaces (F#) on MSDN and Interfaces page at F# for Fun and Profit for more details about how to actually write such interface implementation in F#.
FWIW, the (more or less) direct translation of MyObjectX is
type MyObjectX() =
let mutable operationMode = 0
let mutable sp : ISignalProvider = Unchecked.defaultof<ISignalProvider>
member this.SetSignalProvider signal = sp <- signal
interface IMathSolver with
member this.MethodMathSolver () =
sp.GetThreshold()
//
0.0
member this.Method2MathSolver provider =
let x = provider.GetValueAtTime 0.1
//
x
interface IBusinessSolver with
member this.Method1BusinessSolver () = 0.0
although I had to guess at a couple of the interface definitions.
However, this isn't particularly functional. For more information about moving from an object-oriented to a functional mindset, see
https://stackoverflow.com/a/22266609/126014
http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional
So long as the interface is defined in an assembly referenced by the F# project you can just implement MyObjectX directly
type MyObjectX(signal : ISignalProvider) =
let mutable operationMode : int = 0; // assuming this changes
interface IMathSolver with
member x.GetMethodMathSolver() : double =
signal.GetThreshold()
// ...
member x.MethodBusinessSolver() : double =
...
Take a look at the F# documentation. It is possible to create .NET classes and interfaces trivially and to use those within the language.
If you are looking to use IoC, you should have no problem injecting an F# implementation into a C# module and vice versa. Just have a play!
I'd say go for (1).
That way, you'll have make your life easier referencing F# from other F# code, and the wrapper should be trivial to write. That will aslo add a level of indirection, letting you change the C# interface or the F# code without affecting the other side of the system.

what are the use of interfaces and diffrences with respect to inheritance

What are the major advantages of interfaces in designing application and the differences with respect to inheritance. can any body provide me with the brief example.
Objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.
In its most common form, an interface is a group of related methods with empty bodies.
A bicycle's behavior, if specified as an interface, might appear as follows:
interface IBicycle {
void changeCadence(int newValue); // wheel revolutions per minute
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:
class ACMEBicycle : IBicycle {
// remainder of this class implemented as before
}
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
You can find more details also checking difference between Interface and Class.
The only differences between interfaces and classes is:
Interfaces cannot have implementation
Classes can only be singly inherited
Interfaces are best used in places where:
Multiple class shared functionality on a conceptual level, but do not actually share code.
Where there is a hard separation between provider and user of a class, when the provider does not wish to share any details of the class itself. (This does not necessarily mean secrecy --- In WCF, the user & provider of a class may be separated by the internet; the user would need to have the interface to access the remote object)
An advantage of using interfaces is that you can use mocked objects during your unit tests.
E.g. When a method requires a DbConnection instance, you have to provide it - which can be very difficult within a small test. But when it requires a IDbConnection you can provide a mockup.
There is a tag "mocking" on SO.
Interfaces are used extensively in many advanced design patterns. Especially if the application design uses any sort of Dependency Injection or Inversion of Control.
For instance, a plug-in (add-on) model typically uses interfaces to define the plugin. There will be an interop library (DLL), strictly versioned, which defines the interfaces that can/should/must be implemented by any plug-ins to be consumed by the app.
The application project references the interop library, which allows it to consume any classes that implement those interfaces, without requiring direct references to the actual classes.
The concrete implementations of the plug-ins reference the interop library so that the classes in it can implement the required interfaces. The app has no direct knowledge of the plug-in library, and the plug-in library has no direct knowledge of the app. The can only potentially communicate through the interop interfaces.
In the plug-in scenario, it's common for the app to have a designated folder where plug-ins are located. At run-time, it scans the folder for assemblies, scans each assembly for classes/structs, examines each class/struct for known (interop) interfaces, and dynamically loads whatever matching plug-ins it finds by interface. Depending on the mechanism, each plug-in is usually added to a menu somewhere so that it can be used by the end user.
In this model, plug-ins can be updated without having to recompile the app, and the app can be updated without having to recompile the plug-ins. As long as the interop library version/signature doesn't change, the app itself or individual plug-ins can be updated/modified/fixed independently without having to redistribute the whole kit-n-kaboodle.
Also, 3rd parties that are going to develop plug-ins for your app only have to focus on implementing specific interfaces from your interop, without having to be concerned with the specifics of how your app consumes them.
Icognito has a good answer (which I upvoted). I only wanted to add the following:
An Interface defines method signatures that any implementing object must have. It enables your code to call methods on those objects without knowing anything else about it.
A class defines method signatures and may define method bodies and properties. A class may implement an Interface. This gives you the ability to keep both data and the manipulation code together.
Icognito's remote example was actually better than the bicycle. A TV might have an Interface like:
interface ITelevision {
void TogglePower();
void ChangeChannel( Int32 channel);
}
A couple of objects that might deal with that interface would be one or more TV objects and a Remote object like:
class SonyTelevision: ITelevision {
public void TogglePower {
//Perform the operation to turn the TV on or off
}
public void ChangeChannel (Int32 channel) {
// Perform the operation of changing the channel
}
}
class ToshibaTelevision: ITelevision {
public void TogglePower {
//Perform the operation to turn the TV on or off
}
public void ChangeChannel (Int32 channel) {
// Perform the operation of changing the channel
}
}
class Remote {
private _television : Object; // here we don't care what kind of TV it is.
public void ToggleTvPower {
ITelevision tv = _television as ITelevision;
tv.TogglePower();
}
}
In the above, both the Sony and Toshiba manufacturer might have their own class hierarchy for the TV's. However, they both implement the common ITelevision interface which makes coding against those classes MUCH easier.
Note also that an interface means that implementation is left up to the implementing class. At the end of the day as long as everyone implements ITelevision the any remote will be able to control any TV. Even future ones...
A final note: Abstract classes are similar to Interfaces in that abstract classes require descendants to provide the method bodies. However, because a class may only inherit from a single parent class whereas a class may implement as many interfaces as you want.

Categories

Resources