Hi,
is it possible to create buffer in managed memory and to pass a pointer
to it to the unmanged code? Is it possible to do it as a field in the
structure?
I have a following idea. Managed code is doing a callback to the managed
C# with an argument which is a pointer to the structure, like this:
C++:
struct PutData
{
int Size;
char *Buffer;
};
C#:
[ StructLayout( LayoutKind.Sequential )]
public struct Put
{
public int Size;
public byte[] buffer;
}
Now, managed code is responsible to make the buffer of the given size
and to assign a pointer to it to the buffer field of the structure.
It is doing like this:
Put put = (Put)Marshal.PtrToStructure(dataStruct, typeof(Put));
byte[] buffer = new byte[put.Size];
GCHandle gch = GCHandle.Alloc(buffer, GCHandleType.Pinned);
put.buffer = (byte[])gch.Target;
Marshal.StructureToPtr(put, dataStruct, false);
When callback is finished, managed code can use that buffer, like this:
char *tmp = buffer;
int read = 0, count = 0;
BOOL valid = AfxIsValidAddress(buffer, size, TRUE);
if (!valid)
return -1; // Always !!!
while ((size > 0) && ((read = recv(tcp, tmp, size, 0)) > 0)) {
count += read;
tmp += read;
size -= read;
}
But, it occurs that buffer is invalid! If I comment lines with buffer
checking I get WSAEFAULT error while trying to do reading.
Can anyone has idea what is the problem?
Thank you!
Nenad
Mattias Sjögren - 04 Jun 2005 10:32 GMT
>C#:
>[ StructLayout( LayoutKind.Sequential )]
[quoted text clipped - 3 lines]
> public byte[] buffer;
>}
Make that
public IntPtr buffer;
and use one of the Marshal.Alloc* methods to allocate the buffer. And
don't forget to free it when you're done.
Mattias

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nenad Dobrilovic - 06 Jun 2005 09:44 GMT
>>C#:
>>[ StructLayout( LayoutKind.Sequential )]
[quoted text clipped - 12 lines]
>
> Mattias
Buffer should be allocated in managed memory, but this methods allocate
memory in unmanaged space, as I can see.
Mattias Sjögren - 06 Jun 2005 23:15 GMT
>Buffer should be allocated in managed memory,
Why?
You can try making Put.buffer an IntPtr and then assign
gch.AddrOfPinnedObject to it.
Mattias

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nenad Dobrilovic - 07 Jun 2005 09:00 GMT
>>Buffer should be allocated in managed memory,
>
[quoted text clipped - 4 lines]
>
> Mattias
Thank you, Mattias, that was solution of my problem!
I tried to assign gch.Target to Put.buffer, but it didn't work.
Buffer is in managed memory because there is a lot of computations with
it later in managed part of program.
Is it, for some reason, worse than solution with buffer in unmanaged memory?