Safe to use Numeric.Complex with PInvoke? (It does not have LayoutKind.Sequential) - clr

I want to use System.Numerics.Complex in an unmanaged PInvoke scenario. Using ILSpy, I noticed it does not have a LayoutKind.Sequential attribute assigned.
/// <summary>Represents a complex number.</summary>
[Serializable]
public struct Complex : IEquatable<Complex>, IFormattable
{
private double m_real;
private double m_imaginary;
...
Is it safe to give a pointer to an Complex[] array without conversion to a native function expecting the common memory layout, ie.: Real first, imaginary second? Or could the CLR possibly disorder its real and imaginary attributes for some reason?

LayoutKind.Sequential is default for all major .NET compiler: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.layoutkind.aspx
Even if it wouldn't: theonly reason to alter the order of attributes would be for alignment issues. Since System.Numerics.Complex does only have two double members there would be no reason to exchange them. So IMO you are safe.

You are fine because this is a struct. It has an implied [StructLayout] that's sequential. Something you can see from typeof(Complex).IsLayoutSequential. The same is not true for a class, it requires an explicit declaration.
And yes, fields can get swapped in the internal representation of the object. But that won't matter since the pinvoke marshaller must marshal the object. There's an implied Marshal.StructureToPtr() built into the marshaller. Fwiw, this swapping won't happen because the packing for two doubles is already optimal. They fit without leaving any padding. So the marshaller just creates a pointer to the object and won't have to copy it.
All good news :)

Related

How to return a struct from an imported DLL-function in MQL4?

Is there a way to return a struct from an imported function in MQL4, without having to pass it as a parameter and making a memcpy?
Be cautious with any kind of DLL-interfacing, MQL4 Documentation states:
Passing ParametersAll parameters of simple types are passed by values unless it is explicitly indicated that they are passed by reference. When a string is passed, the address of the buffer of the copied string is passed; if a string is passed by reference, the address of the buffer of this string without copying it is passed to the function imported from DLL.Structures that contain dynamic arrays[], strings, classes, other complex structures, as well as static or dynamic arrays[] of the enumerated objects, can't be passed as a parameter to an imported function.When passing an array to DLL, the address of the beginning of the data buffer is always passed (irrespective of the AS_SERIES flag). A function inside a DLL knows nothing about the AS_SERIES flag, the passed array is a static array of an undefined length; an additional parameter should be used for specifying the array size.
More glitches apply... Then how to make it work?
Maybe a straight, heterogeneous multi-party distributed processing, which communicates rather results than function calls, independent of all nightmares of maintaining just DLL-imported functions API changes, is a way safer way to go. Using this approach for the last few years and since than have no problems with New-MQL4.56789 string-s that seized to remain string-s and silently started to become struct-s etc.
Worth to know about.
Anyway, welcome and enjoy the Wild Worlds of MQL4 -- may enjoy to click and read other posts on issues in MQL4/DLL integration and/or signalling/messaging in MQL4 domains. Feel free to ask more

Why is there no definition for MaskPredicate::operator=(const MaskPredicate&) in OpenCV?

https://github.com/Itseez/opencv/blob/master/modules/features2d/src/keypoint.cpp
The declaration of the function is in line 154.
Making the assignment operator private and unimplemented is a popular way of ensuring that assigments cannot be made (i.e. the compilation will fail).
It is also common to find the same thing done with copy constructors, (although not in this case) so that an object is not copyable.
The underlying reason is usually to do with the internal implementation of the class, which will have been decided by the designers. For example, it makes sense to ensure that a singleton is not copied or assigned, or that an object that contains pointers to other objects is not shallow-copied, causing potential problems at destruction.
In this particular case, the assignment operator was removed as a fix to OpenCV - Bug #419.

Using Dictionary in MonoTouch

I am very confused on the MonoTouch dictionary limitation: http://docs.xamarin.com/ios/about/limitations#Value_types_as_Dictionary_Keys
My understanding that code like this is not allowed:
var foo = new Dictionary<int, int>();
But I see code in books like this, which doesn't make sense:
protected Dictionary<int, CustomCellController> _cellControllers = new Dictionary<int, CustomCellController>();
Also, someone posted that if you use nullable types, it convers the values into reference so the following works (as long as the key is not null):
var foo = new Dictionary<int?, int?>();
That also doesn't make sense, because nullable types are structs which are value types.
So what are the real rules about using dictionaries on a device?
Since no JITin is allowed on devices all code must be compiled with the AOT (ahead of time) compiler.
My understanding that code like this is not allowed:
This limitation is about the difficulties, for the AOT compiler, of determining what will be used at runtime. Such code might work and you'll see such code in samples - but it can also fail depending on what you do with the code (creating a Dictionary is not the problem).
So what are the real rules about using dictionaries on a device?
Using value-types means that the generated code cannot be shared (like it can for reference types). E.g. Using a generic Dictionary with int and long requires separate code, while the same code can be shared for string and CustomCellController.
Finding what Dictionary<int,int> needs is not the issue (it's pretty clear). However it's often in the internals that things gets complicated, e.g. ensuring the right KeyValuePair is generated. Nested generics are also hard to get right.
This is why the first general workaround is to try to hint the AOT compiler about what's needed. If the AOT compiler can find code that requires it to generate what's needed then it will be available at runtime.
The next workaround is to try to use a reference type (e.g. a string) instead of the value-type (since that case is simpler to handle for the AOT compiler).
Finally the AOT compiler is getting better (by each release) and works continues to reduce this (and other) limitation(s). So what you read here might not apply in 3, 6, 12 months...

Delphi - Declaring in class or not?

Just recently, probably because I've been maintaining some old code, I've started to look at how / why I do things. As you do.
Most of my Delphi programming has been picked up in house, or from examples scattered across the web or manuals. And in some things are done just because "that's how I do it"
What I'm currently wondering about is Declaration, of variables, procedures, functions, etc.
When I am working with a form, I will place all my procedures and functions under public or private. Whilst I will try to avoid global vars and constants will generally go under var or const, either in the interface or implementation, depending on where they need to be called (occasionally though they will go in public / private)
Otherwise, if its just a unit I will declare the procedure in the interface and use in the implementation. Some of the code I've been maintaining recently has no interface declaration but instead has everything properly ordered with calls after procedures...
Is there a correct way to do this? Are there rules of what should / should not go in the class? Or is it a style / when you started thing?
Edit to add
My question is not about whether a declaration of a procedure goes in private/public but whether all declarations in a TForm Unit should go in one of these. Similarly should var / const be in one or the other?
Further clarification
I understand that not declaring in interface, or declaring in public/private/etc affects the visibility of procedures/functions to other units in my applicaiton.
The core of my question is why would i not want to declare? - especially when working in a form/unit when placing in private is much more explicit that the thing declared is not available to other units...
Cheers
Dan
Everything that can have a different value depending on the concrete instance belongs to the class, i.e.
TDog = class
strict private
FColor : TColor;
FName : String;
public
property Color : TColor read FColor write FColor;
property Name : String read FName write FName;
end;
Color and name are clearly attributes of each dog (and each dog will have other values here).
General rules:
Fields belong in private (visible in this class and in this unit) or strict private (visible only in this class)
If you need access to fields from other classes, create a public property. This gives you the freedom to change the simple field access to a more sophisticated getter / setter method lateron without changing the interface of your class.
Everything should be as local as possible. If private is enough, there's no need to make it protected (visible in subclasses too). And only make those things public that you really need from the outside.
Forms: only those things that you want to be stored in the DFM file should be published.
Put as much as you can in the implementation section and as little as you can in the interface section. This is also true for uses clauses.
You might be confusing the term global variable. If it's declared in a class it's not a global variable (even if declared public). Global variables (which you correctly consider good to avoid) always go in a var section either in the interface or the implementation section (which is preferrable following the general rules above)
The question seems to deal with scope. In other words, how easily accessible things can or should be.
As a general guideline, you want to reduce the scope of things as much as possible but still keep them accessible enough to be reused. The reason for this is:
that as your system grows and becomes more complex, the things that have are larger scope are more easily accessible.
as a result, they are more likely to be reused in an uncontrolled fashion.
(sounds great) but the problem comes when you want to make changes, and many things use that which you want to change...
it becomes far more difficult to make your changes without breaking something else.
Having said that, there is also a distinction between data (variables, constants, class fields, record attributes) and routines (functions, procedures, methods on classes). You'll want to apply the guidelines far more strictly to data because 'strange use' of data could interfere with some of your routines in highly unexpected and hard to debug ways.
Another thing to bear in mind is the special distinction between global variables and class fields or record attributes:
using global variables there is only one 'value' (term used loosely) for the entire application.
using class fields or record attributes, each new instance of the class or record has its own values independent of other instances.
This does seem to imply that you could use some form of global whenever your application only needs one thing. However, as alluded to earlier: this is not the only reason to avoid globals.
Personally I even tend to avoid global routines.
I'm frequently discovering that things that seemed okay declared global are not as universal as first thought. (E.g. Delphi VCL declares a global Screen object, I work on 2 screens; and many of our clients use 4 to 6.)
I also find it useful to associate routines that could have been global with specific classes as class methods. It generally makes it easier to understand the code.
So listing these 'locations' from largest scope to smallest, you would generally strive to pick locations lower down in the list (especially for data).
interface global
implementation global
interface threadvar
implementation threadvar
published (Note I don't really consider this to be a scope identifier; it's really public scope; "and includes RTTI information" - theoretically, it would be useful to also mark some private attributes as "include RTTI".)
public
protected
private
strict private
local variable
I must confess: what I have presented here is most certainly an over-simplification. It is one thing to know the goals, another to actually implement them. There is a balancing act between encapsulation (hiding things away) and exposing controlled interfaces to achieve high levels of re-usability.
The techniques to successfully balance these needs fall into a category of far more complicated (and sometimes even contentious) questions on system design. A poor design is likely to induce one to expose 'too much' with 'too large' a scope, and (perhaps paradoxically) also reduce re-usability.

Regarding F# Object Oriented Programming

There's this dichotomy in the way we can create classes in f# which really bothers me. I can create classes using either an implicit format or an explicit one. But some of the features that I want are only available for use with the implicit format and some are only available for use with the explicit format.
For example:
I can't use let inline* (or let alone) inside an explicitly defined class.
The only way (that I know) to define immutable public fields (not properties*) inside an implicitly defined class is the val bla : bla syntax.
But there's a redundancy here. Since I'll end up with two copy of the same immutable data, one private, one public (because in the implicit mode the constructor parameters persist throughout the class existence)
(Not so relevant) The need to use attributes for method overloading and for field's defaults is rather off putting.
Is there anyway I can work around this?
*For performance reasons
EDIT: Turns out I'm wrong about both points (Thanks Ganesh Sittampalam & MichaelGG).
While I can't use let inline in both implicit & explicit class definition, I can use member inline just fine, which I assume does the same thing.
Apparently with the latest F# there's no longer any redundancy since any parameters not used in the class body are local to the constructor.
Will be gone in the next F# release.
This might not help, but you can make members inline. "member inline private" works fine.
For let inline, you can work around by moving it outside the class and explicitly passing any values you need from inside the scope of the class when calling it. Since it'll be inlined, there'll be no performance penalty for doing this.

Resources