I'm working with a GIS based math library that wraps lower C/C++ code in C#. Many of the parameters are pass by reference for the sake of receiving multiple outputs. If I only want some of the outputs, how can I ignore the other parameters? Is the best solution to create a dummy variable and pass it by reference and ignore its output?
Is the best solution to create a dummy variable and pass it by reference and ignore its output?
Yes, that's what I do.
I usually just create an object in my code like
object NotNeeded = null;
or something similar that says that its effectively an unnecessary parameter and then use that repeatedly. I'm not sure whether or not that'll work, though, because I'm not sure what the GIS library is doing on the other side. If it needs an actual non-null value for each one, that might be problemeatic.
You have a few choices:
dummies
wrapper methods
change the Interop Imports. Your ref parameters are most likely pointers in C++, and if they allow null then you could change the import to use pointers (IntPtr) and pass null / IntPtr.Zero.
But a few dummies is probably the best (easiest to read) option unless you have really many, many calls.
The "best" is the "only" compile-time method that I am aware of: foo(bar, ref dummy) -- but feel free to wrap away these dummy variables if it makes sense.
If there are instance methods, creating appropriate Extension Methods wrappers can help hide the "useless" dummy variables in a relatively seamless fashion.
Happy coding.
Related
For example, wouldn't this type:
https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx
... having public mutable fields like this:
https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.x.aspx
... single-handedly make consuming F# code's immutability efforts kind of useless?
PS: performance must be preserved, no wrapping or dynamic instantiation of throw-away values.
PPS: I did some research and suspect the answer (negative) but would appreciate some input. It seems like a typical problem when not implementing everything in F# from scratch.
For collections of structs, this is not an issue. The collection remains immutable irrespective of the struct's members, since getting the struct from the collection returns a copy. Altering this copy does not alter the collection's contents.
Elsewhere, structs can be used to write wrappers without additional GC load. This requires to create methods for all features you want to keep and have them call the original methods. Unless the JIT doesn't inline the calls, this shouldn't cost performance. However, when wrapping reference types, this will create an empty default constructor on the wrapper type, resulting in a null reference if this constructor is called.
As a side note, I wouldn't recommend using vector classes from outside F#, since they are not unit-of-measure aware. In my experience, most vectors can be assigned physical units, which makes code safer and more readable.
You are correct, the short answer is no. However, at least in the case of the Vector2 class you show, many of the operations are implemented in an immutable fashion when you use the static versions of the methods. For example
var vecB = Vector2.Normalize(vecA);
is an immutable call. Unless the libraries you are using support some kind of immutability, you are stuck with having to implement the immutable functionality you want to have.
F# has a design goal of being a hybrid of mutable and immutable content so that it can access the rich functionality of .NET libraries when needed.
I have a library whose functionality I want to eventually expose to .NET. The method I want to expose has the following signature:
void DoSomething(std::list<SomeStruct>& someList);
The variable someList gets populated by DoSomething.
I know how to export from the library already. My main question is what would a ".NET friendly" interface look like for this function? I'd assume that std::list is a bad idea if I want to use C# with P/Invokes.
What other options are there? As the caller, I won't know the size of the buffer that I should pass in ahead of time. Also, as the caller, I'd rather not make multiple calls to the function with small fixed-sized buffers nor would I want to pass in a super large buffer.
What's the best practice for this case?
You can define a struct for use in the pinvoke call. Decorate it on native and mnaged sides, so that the packing is the same on each side. As for the variable sized out parameter, you could use ::GlobalAlloc to allocate an array that can then be deallocated in C#. Pass out an item count as well. In C#, the Marshal type has various methods to use to work with a GlobalAlloc'd array.
I Wanted to convert a c# code to j# and somehow managed to get over dllimport and marshalas.
Problem is, when a function has a reference to an object - ref isn't recognized
public static native int Mathod(ref Type type, int flags);
Anyone has any experience with j# and know how to send references to a method (or define a type in a method as a reference)
I'm pretty sure that you can't do this directly.
Everything is passed by value in real Java, and presumably in J# too.
In recent versions of Java you can workaround the restriction by using AtomicReference, but I very much doubt that J# is up-to-date enough to support this.
You could try changing the method signature to accept a single-element Type[] array, and then mutate that array element. This would allow you to achieve a similar outcome to ref. The downside is that you'd need to change the call-site and the method itself to wrap and unwrap the variable in the array. (Although you could create your own custom type to encapsulate the wrapping and unwrapping if it simplifies things.)
I know in Ruby can add and modify method of class dynamically in run time. what about other language? what is C# ,can in this language modify or add some method and ... in run time and dynamically?
I think you are looking for prototype inheritance. A list of languages is mentioned in the same wikipedia page.
There is a similar question on SO which you can look up.
Yes, in C# you can add methods at runtime through reflection and the Emitter object.
In C# 4.0 you can even do it in plain C# code with the Expando object. This is arguably closer to the Ruby way (it's practically a carbon copy if I remember correctly) and a lot easier to use.
Edit: All of this applies to all .NET languages, including VB.Net and F#.
The whole point of static type systems like C#'s is that all functionality defined for a particular type is known (and checked) at compile-time.
If you write
foo.jump(42);
the compiler verifies that whatever type foo has, it supports an operation called jump taking an integer parameter.
Recently, C# got the possibility of having dynamically checked objects through the dynamic type, which basically allows what you described in a very limited context, but nevertheless, the overall language is statically typed.
So what's left are dynamic languages like Ruby, where method existence is just checked at run-time (or call-time).
I think JavaScript can change so called prototypes to add methods to objects and basically achive the same thing as Ruby.
Python excels at this operation - here are bunch of examples: Python: changing methods and attributes at runtime
Lisp's object system is also quite dynamic:
http://en.wikipedia.org/wiki/Common_Lisp_Object_System
"CLOS is dynamic, meaning that not only the contents, but also the structure of its objects can be modified at runtime. CLOS supports changing class definitions on-the-fly (even when instances of the class in question already exist) as well as changing the class membership of a given instance through the change-class operator. CLOS also allows one to add, redefine and remove methods at runtime."
in C# 4 you have dynamic object which you can add/modify at run time.
Before I ask my question, please take a look at this example function:
DateTime.TryParse("01/01/2000", out oDate)
Why do I need to specify the out keyword? Shouldn't the compiler know this from the function's definition?
I'm asking this out of pure curiosity in the hope that I will learn something new about the compiler.
I should also clarify that I'm asking about the C# .NET 3.5 compiler in particular.
The out keyword could be implied by the compiler but my understanding is that the C# team decided to make the out keyword explicitly required by the caller of the function to increase visibility as to the nature of the parameter.
The compiler does know, you may not. It's a way of letting you know that the parameter you are passing can change in this function you are passing it to.
It's not about what the compiler knows, it's all about making sure the developer realizes this call can and will change the value of variable X.
A lot of this has it's roots in C++ where a reference value needs no call site monitor. It's impossible to look at a C++ call and know exactly what it will do. Parameters passed by reference and value in C++ have huge differences in semantics.
Yeah the compiler could figure it out, but this way you know that it is going to modify the variable you are passing in.
the C# language has a lot of what I would call safety nets that explicitely tell the programmer what is going on. A couple of examples are:
No fall through in switch statements.
You can't assign a value in an if statement: if(x = 5) throws an error instead of evaluating to true.
http://msdn.microsoft.com/en-us/library/t3c3bfhx(VS.80).aspx
"The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword."
Since the DateTime.TryParse does not require oDate to be initialized, you must pass the out keyword.
OK, I'm not a C# expert, so if I mess up will somebody please correct me?
There's two ways to pass a parameter to a C# function: by value and by reference. The big difference here is whether modifying the parameter inside the function modifies the variable used to call it. This is not something I'd trust the compiler to decide for itself.
Since you want oDate to be a variable passed in from the caller, and changed, you want it passed by reference.
The other question is whether it should be initialized or not. C# likes to catch when variables are used while uninitialized, since that's almost always an error. In this case, you might well just declare what you're passing in, and use TryParse() to give it its first value. This is a perfectly legitimate technique, so the compiler should allow it. This is another thing I wouldn't trust the compiler to get right. (I assume the compiler also checks to make sure an out parameter is initialized before use in TryParse().)
So, "out" serves two purposes. It establishes that the parameter is passed in by reference, and that it is expected to be initialized inside the function. Neither of these can be determined by the compiler.