DynamicMethod in Cecil - mono

Is there anything similar to Reflection.Emit.DynamicMethod in Cecil? Thanks.
DynamicMethod
Edit:
What about for the following things?
EmitCall (e.g.
IL.EmitCall(OpCodes.Callvirt, GetBuildKey, null);
IL.Emit(OpCodes.Unbox_Any, dependencyType);
)
LocalBuilder (e.g. LocalBuilder resolving = ilContext.IL.DeclareLocal(typeof(bool));)
System.Reflection.Emit.Label (e.g. Label existingObjectNotNull = buildContext.IL.DefineLabel();) //Do I have to use TextMap?
ILGenerator.BeginCatchBlock (e.g. ilContext.IL.BeginCatchBlock(typeof(Exception)); )
ILGenerator.MarkLabel (e.g. ilContext.IL.MarkLabel(parameterResolveFailed); )
ILGenerator.EndExceptionBlock() (e.g. ilContext.IL.EndExceptionBlock(); )

There's no way to create a DynamicMethod with Cecil, nor does it have an equivalent.
A DynamicMethod is strongly tied to the runtime, while Cecil is completely decoupled. The two of them have a completely separate type system. DynamicMethod are meant to be, well, dynamic, and as such have to use the System.Reflection type system, as it's the one available at runtime. Mono.Cecil has another representation of this type system suitable to static analysis, without having to actually load the assembly at runtime. So if you want to use a DynamicMethod, you have to use it along with its environment.
This question was originally asked, iirc, in the context of runtimes without DynamicMethods or SRE all-together, like the Compact Framework, where Cecil can be used to emit code at runtime.
Of course it's possible, but then you have to pay the price of loading the assembly, which is no small price on CF devices. It means that if you could somehow emulate a DynamicMethod by creating an assembly with only one static method with Cecil, it sounds a terrible idea. The assemblies would not be collectable (DynamicMethods are), making it a giant memory leak.
If you need to emit code at runtime on the Compact Framework, emit as less as possible, and emit as few assemblies as possible.

Related

Advantage of FsXaml type provider over XamlReader

F# doesn't support partial classes nor precompilation of XAML files. The workaround: instead of compile-time code behind, load graphical object definitions at runtime. There are various ways to supply XamlReader with the content of a referenced resource file.
open System.Windows
// from Resource
let uri = System.Uri "pack://application:,,,/AssemblyName;component/MainWindow.xaml"
let info = Application.GetResourceStream uri
let wnd = Markup.XamlReader.Load info.Stream :?> Window
// from Embedded resource
let assembly = System.Reflection.Assembly.GetExecutingAssembly()
let stream = assembly.GetManifestResourceStream "MainWindow.xaml"
let wnd = Markup.XamlReader.Load stream :?> Window
Type providers should be able to shift at least part of that effort back to compile-time.
open FsXaml
type MainWindow = XAML<"MainWindow.xaml">
let mainwnd = new MainWindow()
let wnd = mainwnd.Root
The gain in type safety (and discovery) seems to be marginal: one runtime type cast less per resource. Are there other advantages?
The gain in type safety (and discovery) seems to be marginal: one runtime type cast less per resource.
There are other advantages here, even in the code you displayed. Using FsXaml is far more concise in your example, and fully type safe. It will also fail at compile time if there are major issues in your XAML files, where using XAML Loader defers this to runtime.
Are there other advantages?
There are many advantages -
Shorter code
Type safety
Named elements exposed as properties in a type safe manner
(Most important) Creates actual types corresponding to your XAML types
The last point is really the "killer" advantage of FsXaml vs XamlReader - without this, it's nearly impossible to do anything beyond "toy" projects in WPF. You need to have "real types" corresponding to your types if you want to be able to embed XAML.
For example, if you want to use UserControls you develop as data templates, you need that UserControl to be an actual type, not just some XAML as a resource. Using XamlReader, there's no way to reference that from other XAML. You also can't reuse resources, pull data into your Application, or many other things (without resorting to hand-writing a huge amount of plumbing to do it at runtime).
In addition, with FsXaml 2+, you can subclass types and provide full logic within the "code behind", similarly (though differently) from how you work in C#.
This brings Xaml much, much closer to the experience when working in C# - There is still no BAML compilation (the one disadvantage), but otherwise, you get an experience that is effectively on-par with C# when working from F# with WPF.
A type provider checks things at compile time, the Xaml reader works at run time. Thus errors are either detected at compile or at run time. It is pretty obvious that finding errors earlier in the development process is better.

keep around a piece of context built during compile-time for later use in runtime?

I'm aware this might be a broad question (there's no specific code for you to look at), but I'm hoping I'd get some insights as to what to do, or how to approach the problem.
To keep things simple, suppose the compiler that I'm writing performs these three steps:
parse (and bind all variables)
typecheck
codegen
Also the language that I'm building the compiler for wants to support late-analysis/late-binding (ie., it has a function that takes a String, which is to be compiled and executed as a piece of source-code during runtime).
Now during parse-phase, I have a piece of context that I need to keep around till run-time for the sole benefit of the aforementioned function (because it needs to parse and typecheck its argument in that context).
So the question, how should I do this? What do other compilers do?
Should I just serialise the context object to disk (codegen for it) and resurrect it during run-time or something?
Thanks
Yes, you'll need to emit the type information (or other context, you weren't very specific) in your object/executable files, so that your eval can read it at runtime. You might look at Java's .class file format for inspiration; Java doesn't have eval as such, but you can dynamically spin new bytecode at runtime that must be linked in a type-safe manner. David Conrad's comment is spot-on: this information can also be used to implement reflection, if your language has such a feature.
That's as much as I can help you without more specifics.

Class versioning

I'm looking for a clean way to make incremental updates to my code library, without breaking backwards compatibility. This could mean adding new members to classes, or changing existing members to provide additional functionality. Sometimes I am required to change a member in such a way that it would break existing code (e.g. renaming a method or changing its return type), so I'd rather not touch any of my existing types once they are shipped.
The way I currently set this up is through inheritance and polymorphism by creating a new class that extends the previous "version" of that class.
The way this works is by creating the appropriate version of StatusResult (e.g. StatusResultVersion3), based on the actual value of the ProtocolVersion property, and returning it as an instance of CommandResult.
Because .NET does not seem to have a concept of class versioning, I had to come up with my own: appending the version number to the end of the class name. This will no doubt make you cringe. I could easily imagine yourself scratching your eyes out after zooming in on the diagram. But it works. I can add new members and override existing members, without introducing any code breaking changes.
Is there a better way to version my classes?
There are typically two approaches when considering existing code and assembly updates:
Regression Testing
This is a great approach for non-breaking changes, where you can simply overload functions to provide new parameters, etc. Visual Studio has some very advanced unit testing capabilities to make your regression testing relatively easy and automated.
Assembly Versions
If your changes are going to start breaking things, like rewriting the way some utility works, then it's time for a new assembly version. .NET is very good about working with assembly versions. You can deploy the versioned assemblies to different folders so that existing code can continue to reference the old version while new code can take advantage of the features in the new version.
The problem with interfaces is that once published they're largely set in stone. To quote Anders Hejlsburg:
... It's like adding a method to an interface. After you publish an interface, it is for all practical purposes immutable, because any implementation of it might have the methods that you want to add in the next version. So you've got to create a new interface instead.
So you can never just update an interface, you need to create a completely new one. Of course, you can have a single class implement both interfaces so your maintainability effort is fairly low compared with (say) polymorphic classes where your code will become spread out between multiple classes over time.
Multiple Interfaces also allows you to remove methods in a way that classes do not (Sure, you can Deprecate them but that can result in very noisy intellisense after a few iterations)
I personally lean towards having entirely stand-alone versions of the interface in each assembly version.
That is to say...
v 0.1.0.0
interface IExample
{
String DoSomething();
}
v 0.2.0.0
interface IExample
{
void DoSomethingElse();
}
How you implement them behind the scenes is up to you, but most likely it'll be the same classes with slightly different methods doing similar jobs (otherwise, why use the same interface?)
All the old code should be referencing 0.1.x.x and new code will reference 0.2.x.x. About the only issue is when you find (say) a security flaw and the fix needs to be back-ported to an earlier version. This is where a decent VCS comes in (Personal preference is TFS but SVN or anything else which supports branching/merging will do).
Merge the fixes from the 0.2 branch back into the 0.1 branch and then do a recompile to result in (say) 0.1.1.0.
As long as you stick to a process like this:
Major or Minor build will increment if there are any breaking changes (aka signatures will not change on Build/Revision increments)
Use publisher policies if the new Major/Minor version should be used by older programs (equivalent to guaranteeing nothing broke so use the new version anyway)
References in client apps should point at a Major/Minor version but not specify revision/build
This gives you:
A clean codebase without legacy clutter
Allows clients to use the latest version with no code changes if nothing has broken
Prevents clients using newer versions of an assembly which do have breaking changes until they recompile (and, one hopes, update their code as appropriate to take advantage of the new features.)
Allows you to release security patches for previous versions
The OP solved his problem as indicated by this comment:
In the end, I went with the interfaces idea because it allows me to keep multiple versions of a class member in a single class file. When I need to update the class, I'll just add the new interface, shadowing the member that has been changed, and change the return type on some of my methods. This works without breaking backwards compatibility because of polymorphism.
If this is mainly for serialization, This can be achieved in .Net using DataContractSerializers and DataAnnotations. They can deserialize different versions an object into the same object to allow for different versions of the same class to be deserialized, leaving any properties it can't map blank.

Is it OK to use boost::shared ptr in DLL interface?

Is it valid to develop a DLL in C++ that returns boost shared pointers and uses them as parameters?
So, is it ok to export functions like this?
1.) boost::shared_ptr<Connection> startConnection();
2.) void sendToConnection(boost::shared_ptr<Connection> conn, byte* data, int len);
In special: Does the reference count work across DLL boundaries or would the requirement be that exe and dll use the same runtime?
The intention is to overcome the problems with object ownership. So the object gets deleted when both dll and exe don't reference it any more.
According to Scott Meyers in Effective C++ (3rd Edition), shared_ptrs are safe across dll boundaries. The shared_ptr object keeps a pointer to the destructor from the dll that created it.
In his book in Item 18 he states, "An especially nice feature of
tr1::shared_ptr is that it automatically uses its per-pointer deleter
to eliminate another potential client error, the "cross-DLL problem."
This problem crops up when an object is created using new in one
dynamically linked library (DLL) but is deleted in a different DLL. On
many platforms, such cross-DLL new/delete pairs lead to runtime
errors. tr1::shared_ptr avoid the problem, because its default deleter
uses delete from the same DLL where the tr1::shared_ptr is created."
Tim Lesher has an interesting gotcha to watch for, though, that he mentions here. You need to make sure that the DLL that created the shared_ptr isn't unloaded before the shared_ptr finally goes out of scope. I would say that in most cases this isn't something you have to watch for, but if you're creating dlls that will be loosely coupled then I would recommend against using a shared_ptr.
Another potential downside is making sure both sides are created with compatible versions of the boost library. Boost's shared_ptr has been stable for a long while. At least since 1.34 it's been tr1 compatible.
In my opinion, if it's not in the standard and it's not an object/mechanism provided by your library, then it shouldn't be part of the interface to the library. You can create your own object to do the reference counting, and perhaps use boost underneath, but it shouldn't be explicitly exposed in the interface.
DLLs do not normally own resources - the resources are owned by the processes that use the DLL. You are probably better off returning a plain pointer, which you then store in a shared pointer on the calling side. But without more info it's hard to be 100% certain about this.
Something to lookout for if you expose raw pointers from a dll interface. It forces you to use the shared dll CRT, memory allocated in one CRT cannot be deallocated in a different CRT. If you use the shared dll CRT in all your modules ( dll's & exe's ) then you are fine, they all share the same heap, if you dont you will be crossing CRT's and the world will meltdown.
Aside from that issue, I agree with the accepted answer. The creation factory probably shouldn't define ownership & lifecycle management for the client code.
No it is not.
The layout of boost::shared_ptr<T> might not be the same on both sides of the DLL boundary. (Layout is influenced by compiler version, packing pragmas, and other compiler options, as well as the actual version of the Boost source code.)
Only "standard layout" (a new concept in C++11, related to the old "POD = plain old data" concept) types can safely be passed between separately-built modules.

When To Change a GUID on a Type Library

I know that when you add/change/remove methods in a COM interface you're supposed to change the interface/coclass GUID but what about type libraries. When should you change the type library's GUID? Do you change it if a GUID inside the type library has changed? Or should you only change it when something that doesn't have its own GUID within the type library changes.
The basic principle is that COM interfaces and Type Libraries should be immutable (that is, they shouldn't ever change). If you change one item inside a COM interface, then the new version needs to be a completely separate entity from the previous version. The only way to do this is to change the GUID for every interface in the library and the GUID for the type library itself. It's also a good idea (for your own personal sanity) to change the name of the type library.
Ideally you shouldn't ever change a COM interface. Instead create a new derived COM interface and publish in a new type library.
I've got a similar question.
I had an original control with CLSID_A that implemented interface IID_A in some 1.0 type library with GUID_A
Later on, I decided to add a new interface to the original control. It would then implement both IID_A and IID_B interfaces. I figured that I should probably keep the same CLSID but didn’t knew much what to do with the typelib itself. I was mostly doing VC++ programmatic-by-the-book stuff which involved QueryInterface and didn’t cared much about versioning and typelib. You wanted to create an object with a specific CLSID, you just asked CoCreated instance...and then Queried interface for potential support of the new interface...
Now when I get into fancier environments like LabVIEW or design-time drop-in development environments like Microsoft .NET, MFC stuff that seems to break.
You are mentioning in your answer to change all of the GUID. Is the whole paradigm of adapting an application based on available functionality dead, that a newer application could still use its basic functionality with the older version of a control? Maybe I didn’t catch the later wave that is: No point in adapting an application to run using old control version, it simply requires a specific control version. That would be reason M$ also came out with the ASSEMBLY thing.