This question already has answers here:
What is void* in C#? [duplicate]
(7 answers)
Closed 6 years ago.
I need to be able to pass a context object when i register a call back using the following method, which is linked to a C++ DLL file so cant change the method parameters. The callback returns this as one of the arguments when the callback method is executed.
public static void RegisterCallback(UInt32 instance, CALLBACK callbackFunction, UInt32 context)
The last argument is the only one I'm having trouble with. I'm assuming that its meant to be the memory address (or a reference) of the object.
The C++ code has this argument as void*
Any ideas?
This is very common in a C-style api that permits registering a callback. It plays the exact same role as, say, IAsyncResult.AsyncState in managed code for example. The callback gets the value back, it can use it for any purpose it likes. Could be an index in an array of objects for example. Could be a state variable. In the case of C++, it very commonly is the this pointer of the C++ object. Very handy, permits calling an instance function of the C++ object. Anything goes.
Do note that it is pretty unlikely that you need it. First hint that you don't is that you just don't know what to use it for. And that's pretty likely in C# because you already have context. The delegate you use for the callbackFunction argument already captures the this object reference. So any state you need in the callback method can already be provided by fields of the class. Just like C++, minus the extra call.
So don't worry about it, pass 0. Or really, fix the declaration, the parameter should be IntPtr, pass IntPtr.Zero. Probably also what you should do for the instance argument, it quacks like a "handle". A pointer under the hood.
And be careful with the callbackFunction argument, you need to make sure that the garbage collector does not destroy the delegate object. It does not know that the native code is using it. You have to store it in a static variable or call GCHandle.Alloc() so it is always referenced.
Related
I was recently reading an answer about CS1628, "Cannot use ref or out parameter 'parameter' inside an anonymous method, lambda expression, or query expression".
The answer stated a way around this is to implement "ref parameters as boxes" in the CLR.
C# compiler error CS1628 with VS2010/C#4
I am unsure what this means and seem to be unable to find any references to it in google.
Can anyone please explain this to me as its way over my head?
You can declare a "box" class:
class Box<T> { public T Value; }
Pass an instance of that class to the method that you cannot use ref with. The method can reach into the object and mutate Value. The caller can later extract Value.
This works (in constrast to ref) because Box is allocated on the heap and has "infinite" lifetime. ref can only refer to locations with more restricted lifetime.
Why are they termed differently?
Isn't the nature/purpose/place of a function identical to that of a method?
Functions stand alone and methods are members of a class. That's all. (it's really all the same.)
A method is a function that is attached to an object.
JavaScript functions are usually referred to as methods when used in the context of an object.
e.g. document.getElementById('foo') uses the getElementById method.
Function is a very old term meaning a segment of code that accomplishes some task (does some function, if you will).
Method is a relatively newer term (came with OO programming) that means a function that belongs to a specific instance of an object.
All methods are functions, but not all functions are methods.
See this related question from the programmers stackexchange.
You usually find the term function when dealing with procedural code. OOP uses the term method but they are the same thing.
A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).
All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.
It is implicitly passed the object for which it was called
It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)
Also, another answer: Difference between function and method?
Well, its all about the names, but generally functions and methods are the same thing, and of course have the same purpose.
It all began with the first programming languages, where they where called functions, but as more higher level programming languages arose, i guess they thought to name them methods even if they are and serve the sasme purpose.
EDIT:
Functions are not part of any object or class.
Methods are a memeber of an object or class.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Read-only (“const”-like) function parameters of C#
Why is there no const member method in C# and const parameter?
Having programmed in C++ in the past, I recall we could make a constant reference/pointer parameter in a method.
If my memory is correct, the below means, that the method cannot alter the reference and the reference itself is a constant reference.
C++ example
void DisplayData(const string &value) const
{
std::count << value << endl;
}
Is there an equivalent in C# for methods in a class?
The reason why I'm asking is, I'm trying to pass a object by reference (for speed) and at the same time don't want anyone to alter it.
Update 16/09/2020
There now appears to be the in parameter modifier that exhibits this behaviour (in essence, a ref readonly). A brief search on when you would ever use this yields the following answer:
Why would one ever use the "in" parameter modifier in C#?
Original Answer
There is no equivalent for C# and it has been asked many, many, many, many times before.
If you don't want anyone to alter the "reference", or perhaps you mean the content of the object, make sure the class doesn't expose any public setters or methods of mutating the class. If you cannot change the class, have it implement an interface that only publicly exposes the members in a read-only fashion and pass the interface reference instead.
If you mean you want to stop the method from changing the reference, then by default if you pass it "by reference", you are actually passing the reference by value. Any attempt from the method to change what the reference points to will only affect the local method copy, not the caller's copy. This can be changed by using the ref keyword on a reference type, at which point the method can point the reference at a new underlying object and it will affect the caller.
For value types (int, double, byte, char,...,struct) the arguments come in as values and therefore are guaranteed not to affect that calling module.
For string type, although it is a reference type, it is immutable by the CLR, such that nothing you do inside the procedure can affect the original string.
For other reference types (class) there is no way to guarantee changes in the class from the method.
While thinking a little bit about programming in Java/C# I wondered about how methods which belong to objects are represented in memory and how this fact does concern multi threading.
Is a method instantiated for each object in memory seperately or do
all objects of the same type share one instance of the method?
If the latter, how does the executing thread know which object's
attributes to use?
Is it possible to modify the code of a method in
C# with reflection for one, and only one object of many objects of
the same type?
Is a static method which does not use class attributes always thread safe?
I tried to make up my mind about these questions, but I'm very unsure about their answers.
Each method in your source code (in Java, C#, C++, Pascal, I think every OO and procedural language...) has only one copy in binaries and in memory.
Multiple instances of one object have separate fields but all share the same method code. Technically there is a procedure that takes a hidden this parameter to provide an illusion of executing a method on an object. In reality you are calling a procedure and passing structure (a bag of fields) to it along with other parameters. Here is a simple Java object and more-or-less equivalent pseudo-C code:
class Foo {
private int x;
int mulBy(int y) {
return x * y
}
}
Foo foo = new Foo()
foo.mulBy(3)
is translated to this pseude-C code (the encapsulation is forced by the compiler and runtime/VM):
struct Foo {
int x = 0;
}
int Foo_mulBy(Foo *this, int y) {
return this->x * y;
}
Foo* foo = new Foo();
Foo_mulBy(foo, 3)
You have to draw a difference between code and local variables and parameters it operates on (the data). Data is stored on call stack, local to each thread. Code can be executed by multiple threads, each thread has its own copy of instruction pointer (place in the method it currently executes). Also because this is a parameter, it is thread-local, so each thread can operate on a different object concurrently, even though it runs the same code.
That being said you cannot modify a method of only one instance because the method code is shared among all instances.
The Java specifications don't dictate how to do memory layout, and different implementations can do whatever they like, providing it meets the spec where it matters.
Having said that, the mainstream Oracle JVM (HotSpot) works off of things called oops - Ordinary Object Pointers. These consist of two words of header followed by the data which comprises the instance member fields (stored inline for primitive types, and as pointers for reference member fields).
One of the two header words - the class word - is a pointer to a klassOop. This is a special type of oop which holds pointers to the instance methods of the class (basically, the Java equivalent of a C++ vtable). The klassOop is kind-of a VM-level representation of the Class object corresponding to the Java type.
If you're curious about the low-level detail, you can find out a lot more by looking in the OpenJDK source for the definition of some of the oop types (klassOop is a good place to start).
tl;dr Java holds one blob of code for each method of each type. The blobs of code are shared among each instance of the type, and hidden this pointers are used to know which instance's members to use.
I am going to try to answer this in the context of C#.There are basically 3 different types of Methods
virtual
non-virtual
static
When your code is executed, you basically have two kinds of objects that are formed on the heap.
The object corresponding to the type of the object. This is called Type Object. This holds the type object pointer, the sync block index, the static fields and the method table.
The object corresponding to the object itself, which contains all the non static fields.
In response to your questions,
Is a method instantiated for each object in memory seperately or do all objects of the same type share one instance of the method?
This is a wrong way of understanding objects. All methods are per type only. Look at it this way. A method is just a set of instructions. The first time you call a particular method, the IL code is JITed into native instructions and saved in memory. The next time this is called, the address is picked up from the method table and the same instructions are executed again.
2.If the latter, how does the executing thread know which object's attributes to use?
Each static method call on a Type results in looking up the method table from the corresponding Type Object and finding the address of the JITed instruction. In case of methods that are not static, the the relevant object on which the method is called is maintained on the thread's local stack. Basically, you get the nearest object on the stack. That is always the object on which we want the method to be called.
3.Is it possible to modify the code of a method in C# with reflection for one, and only one object of many objects of the same type?
No, It is not possible now. (And I am thankful for that). The reason is that reflection only allows code inspection. If you figure out what some method actually means, there is no way you are going to be able to change the code in the same assembly.
This question already has answers here:
Closed 12 years ago.
I am a beginner of C#, and I can't understand delegate.
Can anybody provide me some better links through which I can understand quickly?
Explaining delegates with adequate details id beyond the scope of this answer. I'd point you to few articles that can help you understand this.
http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx
http://msdn.microsoft.com/en-us/library/aa288459(VS.71).aspx
From MSDN..
A delegate in C# is similar to a
function pointer in C or C++. Using a
delegate allows the programmer to
encapsulate a reference to a method
inside a delegate object. The delegate
object can then be passed to code
which can call the referenced method,
without having to know at compile time
which method will be invoked. Unlike
function pointers in C or C++,
delegates are object-oriented,
type-safe, and secure.
A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type. For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance. If you have a delegate object and an appropriate set of arguments, you can invoke the delegate with the arguments.
An interesting and useful property of
a delegate is that it does not know or
care about the class of the object
that it references. Any object will
do; all that matters is that the
method's argument types and return
type match the delegate's. This makes
delegates perfectly suited for
"anonymous" invocation.
Have you checked out the MSDN:
delegate:
A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.
An Introduction to Delegates, the first sentence of which states:
Callback functions are certainly one of the most useful programming mechanisms ever created.
So, if you are familiar with callbacks, you have some understanding of delegates already.