user2377299
user2377299

Reputation: 103

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?

Upvotes: 0

Views: 132

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109577

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

Upvotes: 1

Marshall777
Marshall777

Reputation: 1204

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

Upvotes: 0

Related Questions