[Gtk-sharp-list] Marshaling question
Jonathan Pryor
jonpryor@vt.edu
27 Feb 2003 13:33:33 -0500
Do you want to use unsafe code?
If you want to avoid unsafe code, you'll probably need to create a
temporary buffer and copy:
public override int Read (byte[] buffer, int offset, int count)
{
// construct temporary for vfs call
byte[] b = buffer;
if (offset != 0) {
b = new byte[count];
}
// gnome_vfs_read using b
// copy data from temporary if needed
if (offset != 0) {
for (int i = 0; i != count; ++i)
buffer[i+offset] = b[i];
}
}
If you want to use unsafe code, you can do as your pseudo-code does.
However, it would require marking the method as unsafe and using a fixed
statement to keep the buffer from being moved during a GC:
public override unsafe int Read (byte[] buffer, int offset,
int count)
{
fixed (byte* buf = &buffer[offset]) {
// gnome_vfs_read stuff...
}
}
Note: I haven't tried compiling any of this, but the techniques should
work. You might want to look up additional information about unsafe
code and fixed statements. You'll also want to make sure you don't
suffer from buffer overflows (e.g. verify that
(offset+count)<buffer.Length).
- Jon
On Thu, 2003-02-27 at 13:13, Charles Iliya Krempeaux wrote:
> Hello,
>
> OK, I can't seem to find any good documentation on this,
> so I'll just ask the question. (If anyone does know of
> any good documentation on this, then please let me know.)
>
>
> I am creating C# a method with the following signature:
>
> public override int Read(byte[] buffer, int offset, int count);
>
> Here, "buffer" (will eventually) contain the stuff that got read.
> "offset" tells you where to start storing stuff in "buffer".
> ("offset" used a zero based index.) And "count" is the maximun
> number of bytes to read from the current stream. Also, it returns
> the total number of bytes read from the stream.
>
> Now, I'm using this to wrap the GnomeVFS procedure:
>
> GnomeVFSResult gnome_vfs_read(GnomeVFSHandle *handle ,
> gpointer buffer ,
> GnomeVFSFileSize bytes ,
> GnomeVFSFileSize *bytes_read );
>
> The problem I am having is with "buffer" in "gnome_vfs_read". I
> need to get a the get at the pointer for "Read"'s buffer. In
> pseudo code, this is basically what I want to do...
>
> public override int Read(byte[] buffer, int offset, int count)
> {
>
> byte * bufferptr = (byte * ) buffer;
>
> bufferptr = bufferptr + offset;
>
> // ...
>
> Although, I am not sure how to do this. Anyone here have any
> ideas?
>
> (I.e., anyone know how to get a pointer to "buffer"'s memory
> buffer?)
>
>
> See ya