How to know pointer to structure by it's array pointer?

I have structure:

public struct MyStruct
{
   public int a;
   public int b;
   public byte[] mass;
}  

I need: Pass poiner to "mass" array to C++ unmanaged function. And after it done all work it will return me pointer to "mass".

So I have the list of MyStruct. And I need to know what the MyStruct in the list contains returned "mass"(wich pointer to I have). If I know pointer to "mass" can I reduce pointer to 8 bytes and take pointer to MyStruct?

HOW TO :

1.Get IntPtr to "mass" array?

2.Get IntPtr to MyStruct structure?

3.Get MyStruct from IntPtr?

But, do not using any copy procedure, like Marshal.Copy...

Or is there a better way to do what I need ? Can I use pointers like in C++ or IntPtr is enought, and how can I do that?

Answers


Assuming that the memory for the array is allocated by the managed code:

When you pass an array to an unmanaged function via P/Invoke, then by default the array is generally pinned in memory by the marshaller so that the memory used by the array does not have to be copied.

You should not need to use an IntPtr at all - you just need to declare the P/Invoke so that it is accepting an array parameter.

However, things are different if the unmanaged code is allocating memory to be returned to the managed code; then things get MUCH more difficult.

Assuming that's not the case, then if you can show us the "C" function declaration we might be able to come up with a P/Invoke declaration.

(I do have a feeling that your situation may be a bit more complicated though...)

Some useful links for you:

http://msdn.microsoft.com/en-us/library/z6cfh6e6%28v=vs.80%29.aspx

http://msdn.microsoft.com/en-us/library/zah6xy75.aspx

How can I pass a pointer to an array using p/invoke in C#?

And some lower level information about the optimizations that the marshaller makes when calling unmanaged code and passing arrays. Essentially, if it can it doesn't make a copy of the data at all:

http://msdn.microsoft.com/en-us/library/23acw07k%28v=vs.80%29.aspx


Take care as the structure may have some specific memory alignment. You may be interested by this link


Need Your Help

Unit testing of java Servlet with EasyMock

java unit-testing servlets testng easymock

I wanna to test that my servlet throw a specific Exception, I'm new on EasyMock and I don't know which method I have to mock.

Embedded Jetty NotUtf8Exception

jetty url-encoding embedded-jetty

We are running a web application embedded in a jetty container. On a jsp there is a jsp:forward. The values of the jsp:param are ISO-8859-1. How can I tell Jetty, that the URL is ISO-8859-1?