PInvoke and pointers

F

FrankVDL

Hi,

I have some problems executing a method using P/Invoke in my C# 2.0
app.

This is the definition for the original .H file

LDVCode LDVAPI ldv_read(
IN LdvHandle handle, /* session handle (from ldv_open) */
OUT PVOID msg_p, /* pointer to buffer to receive message */
IN SHORT len /* length of buffer to receive message */
);


This is how I translated it to C#

[DllImport("ldv32.dll")]
private static extern short ldv_read(short handle, out IntPtr msg_p,
short len);

The error occurs when i try to read data :

err = (LdvError)ldv_read(_LdvHndl, out ptr, (short) 255);
byte[] buf = new byte[255];
Marshal.Copy(ptr, buf, 0, 255);

This is the exception:
System.AccessViolationException was unhandled
Message="Attempted to read or write protected memory. This is often
an indication that other memory is corrupt."
Source="mscorlib"

What am I doing wrong ?
 
?

=?ISO-8859-2?Q?=A3ukasz?=

Hi,

I have some problems executing a method using P/Invoke in my C# 2.0
app.

This is the definition for the original .H file

LDVCode LDVAPI ldv_read(
IN LdvHandle handle, /* session handle (from ldv_open) */
OUT PVOID msg_p, /* pointer to buffer to receive message */
IN SHORT len /* length of buffer to receive message */
);
OUT doesn't mean that you shoul use out keyword in C#.
This is how I translated it to C#

[DllImport("ldv32.dll")]
private static extern short ldv_read(short handle, out IntPtr msg_p,
short len);

The error occurs when i try to read data :

err = (LdvError)ldv_read(_LdvHndl, out ptr, (short) 255);
byte[] buf = new byte[255];
Marshal.Copy(ptr, buf, 0, 255);

This is the exception:
System.AccessViolationException was unhandled
Message="Attempted to read or write protected memory. This is often
an indication that other memory is corrupt."
Source="mscorlib"

What am I doing wrong ?

msg_p - A pointer to a buffer allocated by your application that will
receive the next uplink message. You must program your application to
ensure that a sufficiently large buffer is available to receive each
message. The length of this buffer is specified by the len parameter.

So where do you allocating memory?

Try this:

[DllImport("ldv32.dll")]
private static extern short ldv_read(short handle, IntPtr msg_p, short len);

IntPtr ptr= Marshal.AllocCoTaskMem(255);
err = (LdvError)ldv_read(_LdvHndl, ptr, (short) 255);
byte[] buf = new byte[255];
Marshal.Copy(ptr, buf, 0, 255);
Marshal.FreeCoTaskMem(ptr);

£ukasz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top