How do I access to an address in memory with c#? - c#

How can read a value of a variable in memeory, as binary, which I have its pointer address for in C#?

This article shows how to use the Win32 ReadProcessMemory function to do it. Note that using the unsafe keyword is not sufficient, as it does not give you the ability to specify an explicit memory location.
How to write a Memory Scanner using C#
http://www.codeproject.com/KB/cs/sojaner_memory_scanner.aspx
To view the relevant code, you will need to download the project source, and examine the MemoryScanner.cs class.

You could also use the Marshal.Read* functions like Marshal.ReadInt32(). Cast the pointer value to an IntPtr and use helper methods in the Marshall class to get at the data.

Use unsafe
http://msdn.microsoft.com/en-us/library/28k1s2k6.aspx

Check out the unsafe keyword. This allows you to access the memory directly, like in C++.
http://msdn.microsoft.com/en-us/library/28k1s2k6.aspx

Related

Is there something like C++ pointer in C#? [duplicate]

I'm writing an application that work with a tree data structure. I've written it with C++, now i want to write it by C#. I use pointers for implementing the tree data structure. Is there a pointer in C# too? Is it safe to use it?
If you're implementing a tree structure in C# (or Java, or many other languages) you'd use references instead of pointers. NB. references in C++ are not the same as these references.
The usage is similar to pointers for the most part, but there are advantages like garbage collection.
class TreeNode
{
private TreeNode parent, firstChild, nextSibling;
public InsertChild(TreeNode newChild)
{
newChild.parent = this;
newChild.nextSibling = firstChild;
firstChild = newChild;
}
}
var root = new TreeNode();
var child1 = new TreeNode();
root.InsertChild(child1);
Points of interest:
No need to modify the type with * when declaring the members
No need to set them to null in a constructor (they're already null)
No special -> operator for member access
No need to write a destructor (although look up IDisposable)
YES. There are pointers in C#.
NO. They are NOT safe.
You actually have to use keyword unsafe when you use pointers in C#.
For examples look here and MSDN.
static unsafe void Increment(int* i)
{
*i++;
}
Increment(&count);
Use this instead and code will be SAFE and CLEAN.
static void Increment(ref int i)
{
i++;
}
Increment(ref count);
Is there pointer in C# too?
Yes, declared using the syntax int* varName;.
Is using of that safe?
No pointers are not safe.
There are safe ways to construct a data structure without pointers. If the nodes are classes, then they'll automatically be reference types so you don't need any pointers. Otherwise, you can box them into a reference.
Yes, there is a pointer:
IntPtr
Wikipedia: "which is a safe managed equivalent to int*, and does not require unsafe code"
There is a great series of Data Structures implemented in .Net on Microsoft Docs.
Data Structures Overview
They include sample code for things like Binary Search Tree, Graph, SkipList, NodeList, etc. The code is quite complete and includes a number of pages of docs about why these structures work, etc.
None of the ones from Microsoft use pointers. In general, you never NEED to use them in C#. There are times when using them would be nice, or they are just the way you think from C++. But you can usually find a way not to use them.
The biggest reasons why not to use unsafe code for pointers is that you lose Medium Trust compliance. You can't run through mechanisms like click once, asp.net websites, and Silverlight doesn't allow them either. Stick with refs and fully managed concepts to ensure your code can run in more places.

Why we need Pointers for assigning a value to a variable in Go/C but not C#/Java

It's a actually a general question, but it occurred now that I'm working with Go and C#.
Say we want to assign a variable from user's input in Go:
func main() {
var input float64
fmt.Scan(&input)
}
It's pretty much clear why we need a memory location to put our new value in. But why in languages like Java or C#, we are not following the same logic:
var input = Convert.ToInt32(Console.ReadLine());
// and not &input ...
Java and C# are higher level languages which abstract most of the memory management and other particular things required in lower level languages like C.
In this case, the Console.ReadLine() function allocates memory to store the console input and copies it to the input variable.
Since these languages have garbage collection, allocating and deallocating memory is done automatically, so the framework don't require you to explicitly pass a memory address to write to, and doesn't expect you to free the memory when you are done using it.
Edit:
See #kostix comment for a great improvement to this answer.
In Go, like C/C++, pointer variables are how types can be passed by reference.
Languages like Java and C# discourage the use of pointer variables. C# has the "ref" keyword and "boxing" for passing value types by reference.
See here for more on "ref": https://msdn.microsoft.com/en-us/library/14akc2c7.aspx
See here for more on "boxing: https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

Pass C# reference to C++ pointer and back

I would like to pass C# reference to C/C++ code(pointer), and than get it back from pointer to C#reference.
I have many pairs (uint,Object). I created sorting mechanism in C code, because its much faster than C#. There is only key(uint) and value(object reference) needed. C code is using key for sorting, and is not changing the value(pointer). Is there any simple way to do it? Do i need to use marshalling? C function will be called many times(maybe even a million times), so i am affraid it will be with marshalling too slow, and i donĀ“t even know how to do it with marshalling. I believe when objects address is changed by GC, address of C# reference is not changed. So there will not be needed to place object in pined memory. Am i right about this?
Now i am able to call C function using DllImport, i am able to store C# reference to C pointer, but i am not able to get address stored in C pointer to C# reference.
Any ideas on how to do this?
It is not possible to pass any variables directly from manged c# code to native c++ code. The solution is pinvoke where you can marshal the data.
This works fine but you should know that this is not everytime the fastes solution. On every call the memory must be copied and maybe converted depending on the data types.
My solution to a similar problem, I had some old code in Fortan.
I convert this code to c, then created a managed c++ project.
In c#, I called this manged c++ project.
the c# code looks like this:
unsafe
{
double* input = (double*)utils.Memory.Alloc(sizeof(double) * n);
double* output = (double*)utils.Memory.Alloc(sizeof(double) * n);
//calling the c++ code
c_plus_plus.code(input,output);
//now output contains the output
// (you can use the same array as input and output
}
I hope this helps.

C# P/Invoke: Pointer to string as error message

I am attempting to use llvmc as a C# library using P/Invokes(because I can't find any .NET bindings).
However, I've a problem. llvmc uses char** for error passing.
An example would be this:
char* error = NULL;
LLVMVerifyModule(PointerToSomeModule, LLVMAbortProcessAction, &error);
What should I do to allow this function to be used in C# code?
EDIT: The example I found also mentions this call:
LLVMDisposeMessage(error);
I just saw the answers and thought this could be an important detail.
A char** argument is troublesome, there is a memory management problem. If you declare the argument as "out string", the P/Invoke marshaller is going to try to free the pointer. That's very unlikely to work, it requires the string to be allocated with CoTaskMemAlloc().
The only other option you have to declare it as "out IntPtr" and marshal the string yourself with Marshal.PtrToStringAnsi(). That will work, beyond an unpluggable memory leak if LLVMC actually expects you to free the pointer. Call it a million times to verify that. There are a few odds that it won't blow since it is an error message, it might return a pointer to a string literal.
The only option left then is to write a wrapper in the C++/CLI language so you can free the pointer.
Take a look at the StringBuilder class. Or you can also simply declare the parameter as an integer out parameter and use Marshal.PtrToStringAnsi.

Access memory address in c#

I am interfacing with an ActiveX component that gives me a memory address and the number of bytes.
How can I write a C# program that will access the bytes starting at a given memory address? Is there a way to do it natively, or am I going to have to interface to C++? Does the ActiveX component and my program share the same memory/address space?
You can use Marshal.Copy to copy the data from native memory into an managed array. This way you can then use the data in managed code without using unsafe code.
I highly suggest you use an IntPtr and Marshal.Copy. Here is some code to get you started.
memAddr is the memory address you are given, and bufSize is the size.
IntPtr bufPtr = new IntPtr(memAddr);
byte[] data = new byte[bufSize];
Marshal.Copy(bufPtr, data, 0, bufSize);
This doesn't require you to use unsafe code which requires the the /unsafe compiler option and is not verifiable by the CLR.
If you need an array of something other than bytes, just change the second line. Marshal.Copy has a bunch of overloads.
I think you are looking for the IntPtr type. This type (when used within an unsafe block) will allow you to use the memory handle from the ActiveX component.
C# can use pointers. Just use the 'unsafe' keyword in front of your class, block, method, or member variable (not local variables). If a class is marked unsafe all member variables are unsafe as well.
unsafe class Foo
{
}
unsafe int FooMethod
{
}
Then you can use pointers with * and & just like C.
I don't know about ActiveX Components in the same address space.

Categories

Resources