Unmanaged pointer

E

eusebiu

Hello... I am making a Sytem.IntPtr with Marshal.AllocHGlobal(int)
(Allocates memory from the unmanaged memory of the process using
GlobalAlloc - MSDN Definition for Marshal.AllocHGlobal) and after
copying the data from a byte[] buffer to the IntPtr(with
Marshal.Copy), I send the IntPtr to an unmanaged library. In the
unmanaged library the function's signature has a unsigned char *
parameter(my IntPtr from C#) and in function's code-block I want to
get the pointer's value.

I use this code to put the pointer's value into a txt file

//C++ code
char* b = new char[10];
sprintf(b,"%2d", (int)pMyPointer);
ofstream out((char *)"aaa.txt");
out.write((const char*)b, 10);
delete[] b;

In C#, when debugging, I have a value for my System.IntPtr but when I
open the txt file, I see other value.

Why is that? Isn't Marshal.AllocHGlobal return pointer a pointer on
the unmanaged heap to an unmanaged memory?
Thanks
 
N

Nicholas Paldino [.NET/C# MVP]

It seems like you are just trying to pass a string to your function.
Why not just use a String parameter and declare the function with the
MarshalAs attribute with a value of UnmanagedType.LPStr?
 
B

Ben Voigt [C++ MVP]

eusebiu said:
Hello... I am making a Sytem.IntPtr with Marshal.AllocHGlobal(int)
(Allocates memory from the unmanaged memory of the process using
GlobalAlloc - MSDN Definition for Marshal.AllocHGlobal) and after
copying the data from a byte[] buffer to the IntPtr(with
Marshal.Copy), I send the IntPtr to an unmanaged library. In the
unmanaged library the function's signature has a unsigned char *
parameter(my IntPtr from C#) and in function's code-block I want to
get the pointer's value.

I use this code to put the pointer's value into a txt file

//C++ code
char* b = new char[10];
sprintf(b,"%2d", (int)pMyPointer);
ofstream out((char *)"aaa.txt");
out.write((const char*)b, 10);
delete[] b;

I think that ought to work, but really, that's some atrocious code. Try
instead:

ofstream out("aaa.txt");
out << hex << pMyPointer << flush;
In C#, when debugging, I have a value for my System.IntPtr but when I
open the txt file, I see other value.

Maybe two different runs of the program? The pointer isn't guaranteed to be
the same every time.

Anyway, is there are reason you aren't using a pinned byte*?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top