C# Memory struct pointer [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on a memory reader/writer class, but i am stuck with it.
My problem is that i want to modify an other process memory values with a struct pointer.
I know how to do it in C++ but not with C#
My current code is:
class CModifier
{
struct Data
{
int iMember;
float fMember;
}
public CModifier()
{
Data data[62];
*data = 0x123456;
// use them to modify values etc.
data.fMember = 1.2345f;
}
}

C# does allow limited access to memory locations, but it is not really recommended, and should only be attempted once you know how other systems such as garbage collection handle your memory. The reference operator & and the de-reference operator * are used for accessing memory. you also must use the unsafe keyword in your method declaration. as an example:
public unsafe void Method()
{
int x = 10;
int y = 20;
int *ptr1 = &x;
int *ptr2 = &y;
Console.WriteLine((int)ptr1);
Console.WriteLine((int)ptr2);
Console.WriteLine(*ptr1);
Console.WriteLine(*ptr2);
}
Note that there are other more advanced things to consider, such as Pinning memory locations to stop the garbage collector from moving the object in memory, and the effect this process would have on your stack heap.
Bottom line, Use pointer references at your own risk, and only as a last resort.

I feel like C++ professionals are going to lambast my post for not using correct technical terms, but oh well.
C# has an 'unsafe' modifier you can use to have pointer-adjusting code, but a better option for modifying structs in another location is the 'ref' keyword.
I can't say -exactly- what you're trying to accomplish can be done in C# (heck, I'm not sure I'd understand it in C++), but here's how I'd do it, as you've described.
void ChangeMyStruct(ref Data etc) {
data.fMember = 1.2345f;
}
void mainMethod() {
ChangeMyStruct(ref dataOne);
}

Related

In c#, how can I manually move the memory that a reference type points to, into a pinned, fixed, contiguous array or buffer? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I need a buffer of memory which holds actual objects, not references, in memory.
I am using Unity Engine for my app. In order to submit a draw-call in Unity, one must provide a Mesh-object and Material-object in the function call. Here
is the part of my algorithm I am trying to optimize.
Mesh[] meshes;
Material[] materials;
Foreach (mesh-type)
DrawMeshInstancedIndirect(mesh[i],material[i]...etc);
I want to be able to iterate over a buffer of memory directly containing the object data, with no references, because I don't want to fill my cpu cache with useless data fetching each object in random parts of memory. You cannot substitute structs for these special Unity classes.
It doesn't matter if it is bad practice or a very messy solution. This is a performance-critical part of my app where structs cannot be substitute for classes.
Here is a reference to the draw-call function, for more context.
https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstancedIndirect.html
Try the fixed keyword.
class Foo
{
public int[] stuff = new int[999];
public unsafe void ExamplePinned()
{
fixed (int* pStuff = stuff)
{
//Alright, the data array is all set and ready to go. Think of 'pStuff' as a pointer
//to the first element in the array. You can use it to access the memory of the
//array and copy it to another buffer
}
}
}

Why accessing a class field via a struct holding a reference to it is faster in C#? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
A few days ago I checked out the C# implementation of Binary Trees test # Computer Language Benchmark Game, and was weirdly surprised: the tree node there is described as a struct (TreeNode) referencing a class (Next) which has two fields of a TreeNode (strut) type. This obviously looks weird, so I updated this code to use a single class (i.e. ~ class TreeNode { TreeNode Left, Right }). My ItemCheck implementation was:
public int ItemCheck()
{
if (ReferenceEquals(Left, null)) // Such a node is always a leaf in this test
return 1;
return 1 + Left.ItemCheck() + Right.ItemCheck();
}
As you may find, it's quite similar to the original implementation. Nevertheless, the performance of this code was ~ 2.2x worse!
Can someone explain why this kind of "optimization" makes sense on .NET? I mostly want to understand what are some other implications of this - of course, if it's not simply a lack in C# / JIT compiler.
A bit more readable version of the same code with a few minor performance improvements can be found here: https://github.com/alexyakunin/BenchmarkGame-CSharp/blob/master/src/BinaryTrees/Program.cs
Update: I created an extra project for benchmarking this:
Code: https://github.com/alexyakunin/BenchmarkGame-CSharp/blob/master/src/Benchmarks/Program.cs
Benchmarking results: https://github.com/alexyakunin/BenchmarkGame-CSharp/blob/master/src/Benchmarks/BenchmarkDotNet.Artifacts/results/TreeNodeBenchmark-report-github.md

Why use int, float etc. instead of object? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've been reading a book on C# and it explains that int, float, double etc. are "basic" types meaning that they store the information at the lowest level of the language, while a type such as 'object' puts information in the memory and then the program has to access this information there. I don't know exactly what this means as a beginner, though!
The book however does not explain what the difference is. Why would I use int or string or whatever instead of just object every time, as object is essentially any of these types?
How does it impact the performance of the program?
This is a very broad subject, and I'm afraid your question as currently stated is prone to being put on hold as such. This answer will barely scratch the surface. Try to educate yourself more, and then you'll be able to ask a more specific question.
Why would I use int or string or whatever instead of just object every time, as object is essentially any of these types?
Basically you use the appropriate types to store different types of information in order to execute useful operations on them.
Just as you don't "add" two objects, you can't get the substring of a number.
So:
int foo = 42;
int bar = 21;
int fooBar = foo + bar;
This won't work if you declared the variables as object. You can do an addition because the numeric types have mathematical operators defined on them, such as the + operator.
You can refer to an integer type as an object (or any type really, as in C# everything inherits from object):
object foo = 42;
However now you won't be able to add this foo to another number. It is said to be a boxed value type.
Where exactly these different types are stored is a different subject altoghether, about which a lot has been written already. See for example Why are Value Types created on the Stack and Reference Types created on the Heap?. Also relevant is the difference between value types and reference types, as pointed out in the comments.
C# is a strongly typed language, which means that the compiler checks that the types of the variables and methods that you use are always consistent. This is what prevents you from writing things like this:
void PrintOrder(Order order)
{
...
}
PrintOrder("Hello world");
because it would make no sense.
If you just use object everywhere, the compiler can't check anything. And anyway, it wouldn't let you access the members of the actual type, because it doesn't know that they exist. For instance, this works:
OrderPrinter printer = new OrderPrinter();
printer.PrintOrder(myOrder);
But this doesn't
object printer = new OrderPrinter();
printer.PrintOrder(myOrder);
because there is no PrintOrder method defined in the class Object.
This can seem constraining if you come from a loosely-typed language, but you'll come to appreciate it, because it lets you detect lots of potential errors at compile time, rather than at runtime.
What the book is referring to is basically the difference between value types (int, float, struct, etc) and reference types (string, object, etc).
Value types store the content in a memory allocated on the stack which is efficient where as reference types (almost anything that can have the null value) store the address where data is. Reference types are allocated on the heap which is less efficient than the stack because there is a cost to allocating and deallocating the memory used to store your data. (and it's only deallocated by the garbage collector)
So if you are using object every time it will be slower to allocate the memory and slower to reclaim it.
Documentation

Is it safe to access a method of C# from an unmanaged C library? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm accessing a method of C# from C now. Below is some snippet of code in C#.
IntPtr pFunc = Marshal.GetFunctionPointerForDelegate (
new DelegateForMyMethodInCsharp (
MyMethodInCsharp
)
);
setFuncPtr(pFunc);
setFuncPtr() is a function of a C library to set the pointer of a C# method. After this code I can call the C# method in the C library whenever I want without any problems but I'm not sure if this is okay.
When using pointers for variables stored in heap in C#, the keyword 'fixed' must be used due to GC. Because the stack section of memory contains methods, it makes sense for me to write code like above. But because I haven't seen people write that way yet, I hope to hear your opinions.
This is a very simple question, but a very important question to me.
I don't want to write unsafe code.
You need to make sure that the delegate instance is not garbage collected.
To do that, you can simply store it in a field, and make sure that field is rooted for as long as the unmanaged code hangs on to the pointer.
This is necessary because delegates store not just a pointer to a .Net method, but also state (the first argument; typically this). To make a function pointer for that, the runtime must create a thunk that refers to this object, so that unmanaged code can get there from nothing but a function pointer. This is bounded by the lifetime of the delegate instance.
For more information on the difference between delegates and function pointers, see my blog.

Declaring variables in another class - pros and cons [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm a beginner in C# and am trying to understand the effects of declaring variables in different scopes. Is there any appreciable performance difference between:
Example 1
class A
{
static int i;
static string temp;
}
class B
{
while(true)
{
A.i=10;
A.temp="Hello";
}
}
Example 2
class B
{
int i;
string temp;
while(true)
{
i=10;
temp="Hello";
}
}
Example 3
class A
{
public int i;
public string temp;
}
class B
{
A D = new A();
while(true)
{
D.i=10;
D.temp="Hello";
}
}
The first code snippet shares both variables: they get allocated statically, and all threads would use them in concurrent environments. This is very bad - one should avoid situations like that in production code.
The second and the third code snippets are thread safe. The third snippet groups variables i and temp; the second snippet does not. In addition, the third snippet needs an extra allocation of an object, and creates an object to be collected upon return (of course it never returns because of the infinite while (true) loop, so it does not really matter).
If the two variables do not belong together logically, you should avoid making a class for them. If they do belong together, you should move the code that uses these variables into the class that declares them.
As far as the performance and memory implications go, the third snippet requires an extra chunk of memory compared to the second one, but it is too small to pay attention to. The performance difference will be nearly impossible to detect, so you should not worry about it much: in most cases, it is best to optimize your code for readability.

Categories