[Q] A PtrToStructure question

  • Thread starter Thread starter Andre
  • Start date Start date
A

Andre

Hi,

I have a question about Marshal.PtrToStructure method.

I have a function Func() in unmanaged C++ which returns a pointer to a
structure Str which is held on the unmanged site:

Str* a = Func(); //unmanaged function

On the managed site I wrote it like this:

[DllImport("UnmanagedFuncs.dll")] IntPtr UnmanagedFunc(); //managed
import of the function


I want to manipulate this structure in managed C# and I use:

IntPtr b = UnmanagedFunc();
Str c = (Str)Marshal.PtrToStructure(b,typeof(Str));
c.Value = 10;

Now my question is:
1) Is c a copy of the structure where b is pointing to?
2) When I manipulate c.Value is this also changed on the unmanaged
site?
3) When 1) is yes and 2) is No how can I change values in the memory
where b is pointing?

Thanks
André Betz
http://www.andrebetz.de
 
Hi,

Andre said:
Hi,

I have a question about Marshal.PtrToStructure method.

I have a function Func() in unmanaged C++ which returns a pointer to a
structure Str which is held on the unmanged site:

Str* a = Func(); //unmanaged function

On the managed site I wrote it like this:

[DllImport("UnmanagedFuncs.dll")] IntPtr UnmanagedFunc(); //managed
import of the function


I want to manipulate this structure in managed C# and I use:

IntPtr b = UnmanagedFunc();
Str c = (Str)Marshal.PtrToStructure(b,typeof(Str));
c.Value = 10;

Now my question is:
1) Is c a copy of the structure where b is pointing to? Yes.

2) When I manipulate c.Value is this also changed on the unmanaged
site? No.

3) When 1) is yes and 2) is No how can I change values in the memory
where b is pointing?

Call Marshal.StructureToPtr after you changed the structure.


(You can also use any of the Marshal.Write* functions to change unmanaged
memory.)


HTH,
greetings
 
See inline ****

Willy.
Andre said:
Hi,

I have a question about Marshal.PtrToStructure method.

I have a function Func() in unmanaged C++ which returns a pointer to a
structure Str which is held on the unmanged site:

Str* a = Func(); //unmanaged function

On the managed site I wrote it like this:

[DllImport("UnmanagedFuncs.dll")] IntPtr UnmanagedFunc(); //managed
import of the function


I want to manipulate this structure in managed C# and I use:

IntPtr b = UnmanagedFunc();
Str c = (Str)Marshal.PtrToStructure(b,typeof(Str));
c.Value = 10;

Now my question is:
1) Is c a copy of the structure where b is pointing to? *** YES.
2) When I manipulate c.Value is this also changed on the unmanaged
site?
*** NO.
3) When 1) is yes and 2) is No how can I change values in the memory
where b is pointing?
*** If you don't like the marshaling overhead, use the struct pointer
returned in an unsafe context like:

struct Str {
int i;
....
}

unsafe {
Str* a = Func();
a->i = 123;
...
}
 
Back
Top