C# memory address and variable - c#

in C#, is there a way to
Get the memory address stored in a
reference type variable?
Get the memory address of a
variable?
EDIT:
int i;
int* pi = &i;
How do you print out the hex value of pi?

For #2, the & operator will work in the same fashion as in C. If the variable is not on the stack, you may need to use a fixed statement to pin it down while you work so the garbage collector does not move it, though.
For #1, reference types are trickier: you'll need to use a GCHandle, and the reference type has to be blittable, i.e. have a defined memory layout and be bitwise copyable.
In order to access the address as a number, you can cast from pointer type to IntPtr (an integer type defined to be the same size as a pointer), and from there to uint or ulong (depending on the pointer size of the underlying machine).
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
class Blittable
{
int x;
}
class Program
{
public static unsafe void Main()
{
int i;
object o = new Blittable();
int* ptr = &i;
IntPtr addr = (IntPtr)ptr;
Console.WriteLine(addr.ToString("x"));
GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);
addr = h.AddrOfPinnedObject();
Console.WriteLine(addr.ToString("x"));
h.Free();
}
}

Number 1 is not possible at all, you can't have a pointer to a managed object. However, you can use an IntPtr structure to get information about the address of the pointer in the reference:
GCHandle handle = GCHandle.Alloc(str, GCHandleType.Pinned);
IntPtr pointer = GCHandle.ToIntPtr(handle);
string pointerDisplay = pointer.ToString();
handle.Free();
For number 2 you use the & operator:
int* p = &myIntVariable;
Pointers of course have to be done in a unsafe block, and you have to allow unsafe code in the project settings. If the variable is a local variable in a method, it's allocated on the stack so it's already fixed, but if the variable is a member of an object, you have to pin that object in memory using the fixed keyword so that it's not moved by the garbage collector.

To answer your question most correctly:
#1 is possible but a bit tricky, and should be only done for debugging reasons:
object o = new object();
TypedReference tr = __makeref(o);
IntPtr ptr = **(IntPtr**)(&tr);
This works for any object and actually returns the internal pointer to the object in memory. Remember the address can change at any moment because of the GC, which likes to move objects across the memory.
#2 Pointers aren't objects and thus don't inherit ToString from them. You have to cast the pointer to IntPtr like so:
Console.WriteLine((IntPtr)pi);

Related

c# how to access unallocated memory

In C# book is written that I'm unable to access unallocated memory. They said that is possible in unsafe context. My question is how this can be done?
I tried something like this:
static void Main(string[] args)
{
unsafe
{
int c;
Console.WriteLine(c);
}
}
With allow unsafe option in project properties. And this code is unable to compile.
The unsafe keyword does not completely alter the language or compilation model, you still need to initialize any variables before using them. If you want to access "unallocated memory", you need to get a pointer to that memory. Here is an example:
unsafe void AccessMemory()
{
const int address = 10000;
byte[] array = new byte[0];
fixed (byte* zero = array)
{
byte* p = zero + address;
}
}
Here we get a pointer to the empty array, which gives the zero pointer. Then we offset that pointer by some amount (address), which results in a pointer to that memory address.

interop with nim return Struct Array containing a string /char* member

interoping nim dll from c# i could call and execute the code below
if i will add another function (proc) that Calls GetPacks() and try to echo on each element's buffer i could see the output in the C# console correctly
but i could not transfer the data as it is, i tried everything but i could not accomplish the task
proc GetPacksPtrNim(parSze: int, PackArrINOUT: var DataPackArr){.stdcall,exportc,dynlib.} =
PackArrINOUT.newSeq(parSze)
var dummyStr = "abcdefghij"
for i, curDataPack in PackArrINOUT.mpairs:
dummyStr[9] = char(i + int8'0')
curDataPack = DataPack(buffer:dummyStr, intVal: uint32 i)
type
DataPackArr = seq[DataPack]
DataPack = object
buffer: string
intVal: uint32
when i do same in c/c++ the type i am using is either an IntPtr or char*
that is happy to contain returned buffer member
EXPORT_API void __cdecl c_returnDataPack(unsigned int size, dataPack** DpArr)
{
unsigned int dumln, Index;dataPack* CurDp = {NULL};
char dummy[STRMAX];
*DpArr = (dataPack*)malloc( size * sizeof( dataPack ));
CurDp = *DpArr;
strncpy(dummy, "abcdefgHij", STRMAX);
dumln = sizeof(dummy);
for ( Index = 0; Index < size; Index++,CurDp++)
{
CurDp->IVal = Index;
dummy[dumln-1] = '0' + Index % (126 - '0');
CurDp->Sval = (char*) calloc (dumln,sizeof(dummy));
strcpy(CurDp->Sval, dummy);
}
}
c# signature for c code above
[DllImport(#"cdllI.dll", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
private static extern uint c_returnDataPack(uint x, DataPackg.TestC** tcdparr);
C# Struct
public unsafe static class DataPackg
{
[StructLayout(LayoutKind.Sequential)]
public struct TestC
{
public uint Id;
public IntPtr StrVal;
}
}
finally calling the function like so:
public static unsafe List<DataPackg.TestC> PopulateLstPackC(int ArrL)
{
DataPackg.TestC* PackUArrOut;
List<DataPackg.TestC> RtLstPackU = new List<DataPackg.TestC>(ArrL);
c_returnDataPack((uint)ArrL, &PackUArrOut);
DataPackg.TestC* CurrentPack = PackUArrOut;
for (int i = 0; i < ArrL; i++, CurrentPack++)
{
RtLstPackU.Add(new DataPackg.TestC() { StrVal = CurrentPack->StrVal, Id = CurrentPack->Id });
}
//Console.WriteLine("Res={0}", Marshal.PtrToStringAnsi((IntPtr)RtLstPackU[1].StrVal));//new string(RtLstPackU[0].StrVal));
return RtLstPackU;
}
how could i produce similar c code as above from Nim ?
it doesn't have to be same code, but same effect, that in c# i would be able to read the content of the string. for now, the int is readable but the string is not
Edit:
this is what i tried to make things simple
struct array of int members
Update:
it seem that the problem is to do with my settings of nim in my windows OS.
i will be updating as soon as i discover what exactly is wrong.
The string type in Nim is not equivalent to the C's const char* type. Strings in Nim are represented as pointers, pointing into a heap-allocated chunk of memory, which has the following layout:
NI length; # the length of the stored string
NI capacity; # how much room do we have for growth
NIM_CHAR data[capacity]; # the actual string, zero-terminated
Please beware that these types are architecture specific and they are really an implementation detail of the compiler that can be changed in the future. NI is the architecture-default interger type and NIM_CHAR is usually equivalent to a 8-bit char, since Nim is leaning towards the use of UTF8.
With this in mind, you have several options:
1) You can teach C# about this layout and access the string buffers at their correct location (the above caveats apply). An example implementation of this approach can be found here:
https://gist.github.com/zah/fe8f5956684abee6bec9
2) You can use a different type for the buffer field in your Nim code. Possible candidates are ptr char or the fixed size array[char]. The first one will require you to give up the automatic garbage collection and maintain a little bit of code for manual memory management. The second one will give up a little bit of space efficiency and it will put hard-limits on the size of these buffers.
EDIT:
Using cstring may also look tempting, but it's ultimately dangerous. When you assign a regular string to a cstring, the result will be a normal char * value, pointing to the data buffer of the Nim string described above. Since the Nim garbage collector handles properly interior pointers to allocated values, this will be safe as long as the cstring value is placed in a traced location like the stack. But when you place it inside an object, the cstring won't be traced and nothing prevents the GC from releasing the memory, which may create a dangling pointer in your C# code.
Try to change your struct to:
public unsafe static class DataPackg
{
[StructLayout(LayoutKind.Sequential)]
public struct TestC
{
public uint Id;
[MarshalAs(UnmanagedType.LPStr)]
public String StrVal;
}
}

Pointer declaration syntax using & and Intptr. Are both identical?

Case 1:
int i;
int* pi = &i;
Case 2:
int i;
IntPtr pi = &i;
Are both cases identical?
My purpose is that:-
I am copying a value to string variable.
Converting string to bytes array
using Marshal.Alloc(sizeofBytesArray) to get IntPtr ptrToArray
marshal.copy(array,0,ptrToArray,sizeofBytesArray)
Sending this ptrToArray to a vb6 application by using a structure and passing structure via SendMessage win32 api.
On VB6 app:-
I am picking up the value from the structure that gives me the address of the array.
using CopyMemory to copy the bytesarray data into a string..
More Code:
string aString = text;
byte[] theBytes = System.Text.Encoding.Default.GetBytes(aString);
// Marshal the managed struct to a native block of memory.
int myStructSize = theBytes.Length;
IntPtr pMyStruct = Marshal.AllocHGlobal(myStructSize); //int* or IntPtr is good?
try
{
Marshal.Copy(theBytes, 0, pMyStruct, myStructSize);
...............
According to the msdn page:-
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
Are both cases indentical?
No, they are not identical,
The difference is in the underlying implementation of IntPtr
forex
int i = 10 ;
int *pi = i ;
int c = *pi ; // would work
but to do the same thing , you have to cast IntPtr to int*
int i =10 ;
IntPtr pi = &i ;
int *tempPtr = (int*)pi ;
int c = *tempPtr ;
The internal representation of IntPtr is like void* but it is exposed like an integer. You can use it whenever you need to store an unmanaged pointer and don't want to use unsafe code.
It has two limitations:
It cannot be dereferenced directly (you have to cast it as a true pointer).
It doesn't know the type of the data that it points to. (because of void*)

Convert Double to Byte*

I need some C# code to convert a double to a byte*. I know I have to use fixed (and unsafe?), but not exactly sure how...
As long as the double variable has stack scope (local variable or method argument), you can simply use a pointer cast. This works because stack scope variables are not subject to moving by the garbage collector and thus don't have to be pinned. Avoids having to convert the double to byte[] first. The same restrictions apply as with the fixed keyword, the pointer is only valid inside the method body:
unsafe void Foo(double d) {
byte* ptr = (byte*)&d;
// Use ptr
//...
}
Exact same thing that the BitConverter class does.
You can do:
unsafe
{
fixed (byte* b = BitConverter.GetBytes(1.2d))
{
// Do stuff...
}
}
or :
public unsafe void YourMethod(double d)
{
fixed (byte* b = BitConverter.GetBytes(d))
{
// Do stuff...
}
}
Use BitConverter.GetBytes method: http://msdn.microsoft.com/en-us/library/a5be4sc9.aspx
double d = 2.0;
byte[] array = BitConverter.GetBytes(d);
Edit: if you need a C-style byte* use:
double d = 2;
byte[] array = BitConverter.GetBytes(d);
IntPtr ptr = Marshal.AllocHGlobal(sizeof(byte) * array.Length);
Marshal.Copy(array, 0, ptr, array.Length);
unsafe
{
byte* pointer = (byte*)ptr;
}
You can start by using BitConverter.GetBytes()
As most people here have stated, you can use fixed, or BitConverter to do this. But mostly, don't. If you need data marshalled, .NET will do this for you. In most cases you do not want to pass references to managed memory to unmanaged functions (as you will have no control over the state of the data, or the references)
'Fixed' will make sure that within the scope, the data will not be moved or released by the garbage collector, and you will get your pointer. However, outside of the fixed block, unmanaged code might still have that pointer, even though the pointer may have been invalidated by the garbage collector, which will promptly make your application fail without any obvious cause.
In .NET, you seldom get any favorable performance increase by using unsafe code, and passing out references to managed data to unmanaged code is not always favorable.
But there are several answers:
byte value = 255;
unsafe
{
byte* ptr = &value; // Assign the address of value to ptr
SomeUnsafeCode(ptr);
}
You don't need to use fixed on stack allocated variables, as they are not garbage collected.
For garbage collected variables, you will need fixed:
byte[] array = SomeGenerator();
unsafe
{
fixed(byte* ptr = array)
{
SomeUnsafeCode(ptr);
}
}
This will pin the array to memory, so that the grabage collector will not touch the array while it is fixed.
Sometimes you would want to pin data over several blocks of code. In this case you would want to use System.Runtime.InteropServices.GCHandle.

IntPtr arithmetics

I tried to allocate an array of structs in this way:
struct T {
int a; int b;
}
data = Marshal.AllocHGlobal(count*Marshal.SizeOf(typeof(T));
...
I'd like to access to allocated data "binding" a struct to each element in array allocated
with AllocHGlobal... something like this
T v;
v = (T)Marshal.PtrToStructure(data+1, typeof(T));
but i don't find any convenient way... why IntPtr lack of arithmetics? How can I workaround this in a "safe" way?
Someone could confirm that PtrToStructure function copy data into the struct variable? In other words, modifing the struct reflect modifications in the structure array data, or not?
Definitely, I want to operate on data pointed by an IntPtr using struct, without copying data each time, avoiding unsafe code.
Thank all!
You have four options that I can think of, two using only "safe" code, and two using unsafe code. The unsafe options are likely to be significantly faster.
Safe:
Allocate your array in managed memory, and declare your P/Invoke function to take the array. i.e., instead of:
[DllImport(...)]
static extern bool Foo(int count, IntPtr arrayPtr);
make it
[DllImport(...)]
static extern bool Foo(int count, NativeType[] array);
(I've used NativeType for your struct name instead of T, since T is often used in a generic context.)
The problem with this approach is that, as I understand it, the NativeType[] array will be marshaled twice for every call to Foo. It will be copied from managed memory to unmanaged
memory before the call, and copied from unmanaged memory to managed memory afterward. It can be improved, though, if Foo will only read from or write to the array. In this case, decorate the tarray parameter with an [In] (read only) or [Out] (write only) attribute. This allows the runtime to skip one of the copying steps.
As you're doing now, allocate the array in unmanaged memory, and use a bunch of calls to Marshal.PtrToStructure and Marshal.StructureToPtr. This will likely perform even worse than the first option, as you still need to copy elements of the array back and forth, and you're doing it in steps, so you have more overhead. On the other hand, if you have many elements in the array, but you only access a small number of them in between calls to Foo, then this may perform better. You might want a couple of little helper functions, like so:
static T ReadFromArray<T>(IntPtr arrayPtr, int index){
// below, if you **know** you'll be on a 32-bit platform,
// you can change ToInt64() to ToInt32().
return (T)Marshal.PtrToStructure((IntPtr)(arrayPtr.ToInt64() +
index * Marshal.SizeOf(typeof(T)));
}
// you might change `T value` below to `ref T value` to avoid one more copy
static void WriteToArray<T>(IntPtr arrayPtr, int index, T value){
// below, if you **know** you'll be on a 32-bit platform,
// you can change ToInt64() to ToInt32().
Marshal.StructureToPtr(value, (IntPtr)(arrayPtr.ToInt64() +
index * Marshal.SizeOf(typeof(T)), false);
}
Unsafe:
Allocate your array in unmanaged memory, and use pointers to access the elements. This means that all the code that uses the array must be within an unsafe block.
IntPtr arrayPtr = Marhsal.AllocHGlobal(count * sizeof(typeof(NativeType)));
unsafe{
NativeType* ptr = (NativeType*)arrayPtr.ToPointer();
ptr[0].Member1 = foo;
ptr[1].Member2 = bar;
/* and so on */
}
Foo(count, arrayPtr);
Allocate your array in managed memory, and pin it when you need to call the native routine:
NativeType[] array = new NativeType[count];
array[0].Member1 = foo;
array[1].Member2 = bar;
/* and so on */
unsafe{
fixed(NativeType* ptr = array)
Foo(count, (IntPtr)ptr);
// or just Foo(count, ptr), if Foo is declare as such:
// static unsafe bool Foo(int count, NativeType* arrayPtr);
}
This last option is probably the cleanest if you can use unsafe code and are concerned about performance, because your only unsafe code is where you call the native routine. If performance isn't an issue (perhaps if the size of the array is relatively small), or if you can't use unsafe code (perhaps you don't have full trust), then the first option is likely cleanest, although, as I mentioned, if the number of elements you'll access in between calls to the native routine are a small percentage of the number of elements within the array, then the second option is faster.
Note:
The unsafe operations assume that your struct is blittable. If not, then the safe routines are your only option.
"Why IntPtr lack of arithmetics?"
IntPtr stores just a memory address. It doesn't have any kind of information about the contents of that memory location. In this manner, it's similar to void*. To enable pointer arithmetic you have to know the size of the object pointed to.
Fundamentally, IntPtr is primarily designed to be used in managed contexts as an opaque handle (i.e. one that you don't directly dereference in managed code and you just keep around to pass to unmanaged code.) unsafe context provides pointers you can manipulate directly.
Indeed, the IntPtr type does not have its own arithmetic operators. Proper (unsafe) pointer arithmetic is supported in C#, but IntPtr and the Marshal class exist for 'safer' usage of pointers.
I think you want something like the following:
int index = 1; // 2nd element of array
var v = (T)Marshal.PtrToStructure(new IntPtr(data.ToInt32() +
index * Marshal.SizeOf(typeof(T)), typeof(T));
Also, note that IntPtr has no implicit conversion between int and IntPtr, so no luck there.
Generally, if you're going to be doing anything remotely complex with pointers, it's probably best to opt for unsafe code.
You can use the integral memory address of the pointer structure using IntPtr.ToInt32() but beware of platform "bitness" (32/64).
For typical pointer arithmetics, use pointers (look up fixed and unsafe in the documentation):
T data = new T[count];
fixed (T* ptr = &data)
{
for (int i = 0; i < count; i++)
{
// now you can use *ptr + i or ptr[i]
}
}
EDIT:
I'm pondering that IntPtr allows you to handle pointers to data without explicitly manipulating pointer addresses. This allows you to interop with COM and native code without having to declare unsafe contexts. The only requirement that the runtime imposes is the unmanaged code permission. For those purposes, it seems like most marshalling methods only accept whole IntPtr data, and not pure integer or long types, as it provides a thin layer that protects against manipulating the content of the structure. You could manipulate the internals of an IntPtr directly, but that either requires unsafe pointers (again unsafe contexts) or reflection. Finally, IntPtr is automatically adopted to the platform's pointer size.
You could use Marshal.UnsafeAddrOfPinnedArrayElement to get address of specific elements in an array using an IntPtr from a pinned array.
Here is a sample class for a wrapper around pinned arrays so that I can use them with IntPtr and Marshaling code:
/// <summary>
/// Pins an array of Blittable structs so that we can access the data as bytes. Manages a GCHandle around the array.
/// https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.unsafeaddrofpinnedarrayelement?view=netframework-4.7.2
/// </summary>
public sealed class PinnedArray<T> : IDisposable
{
public GCHandle Handle { get; }
public T[] Array { get; }
public int ByteCount { get; private set; }
public IntPtr Ptr { get; private set; }
public IntPtr ElementPointer(int n)
{
return Marshal.UnsafeAddrOfPinnedArrayElement(Array, n);
}
public PinnedArray(T[] xs)
{
Array = xs;
// This will fail if the underlying type is not Blittable (e.g. not contiguous in memory)
Handle = GCHandle.Alloc(xs, GCHandleType.Pinned);
if (xs.Length != 0)
{
Ptr = ElementPointer(0);
ByteCount = (int) Ptr.Distance(ElementPointer(Array.Length));
}
else
{
Ptr = IntPtr.Zero;
ByteCount = 0;
}
}
void DisposeImplementation()
{
if (Ptr != IntPtr.Zero)
{
Handle.Free();
Ptr = IntPtr.Zero;
ByteCount = 0;
}
}
~PinnedArray()
{
DisposeImplementation();
}
public void Dispose()
{
DisposeImplementation();
GC.SuppressFinalize(this);
}
}
IMHO Working with PInvoke and IntPtr is as dangerous as marking your assembly as unsafe and using pointers in an unsafe context (if not more)
If you don't mind unsafe blocks you can write extension functions that operate on the IntPtr cast to byte* like the following:
public static long Distance(this IntPtr a, IntPtr b)
{
return Math.Abs(((byte*)b) - ((byte*)a));
}
However, like always you have to be aware of possible alignment issues when casting to different pointer types.

Categories