473,387 Members | 1,529 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

C# 1 - PInvoke - Pinning structures via GCHandle

Hi all,

I want to understand more about how the pinvoke pinning process works.

I'm writing some code that calls DeviceIoControl.
DeviceIoControl provides a generic interface to device drivers.
Its signature is deliberately open-ended so that it can be highly generic.
Refer SDK for more.

I want to access the drive geommetry of an SD-Card via
IOCTL_DISK_GET_DRIVE_GEOMETRY.

I've tried three different methods for calling DeviceIoControl.
Two work, but the third doesn't. I want to know why?

The three methods are presented below,
And are delimited by "//////////////////"

Cheers Steve

//////////////////
//
// Passing an appropriately defined DISK_GEOMETRY structure by ref works..

ie.

[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true,
CharSet = CharSet.Auto)]
private static extern int DeviceIoControl(
IntPtr hDevice, uint dwIoControlCode,
IntPtr lpInBuffer, uint nInBufferSize,
ref DISK_GEOMETRY lpOutBuffer, uint nOutBufferSize,
out uint lpBytesReturned, IntPtr lpOverlapped);

....

DISK_GEOMETRY DiskGeometry = new DISK_GEOMETRY();

....

// This works

DeviceIoControl(
...,
ref DiskGeometry, // StructLayout sequential, packing = 1
(uint) Marshal.SizeOf(typeof(DISK_GEOMETRY), // 24 bytes
...);

//////////////////
//
// Pinning an allocated byte[] and passing via an IntPtr through lpOutBuffer
works
// yes i know you can just pass a byte array by ref

ie.

[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true,
CharSet = CharSet.Auto)]
private static extern int DeviceIoControl(
IntPtr hDevice, uint dwIoControlCode,
IntPtr lpInBuffer, uint nInBufferSize,
IntPtr lpOutBuffer, uint nOutBufferSize,
out uint lpBytesReturned, IntPtr lpOverlapped);

....

byte[] DiskGeometry = new byte[24];
GCHandle PinnedDiskGeometry = GCHandle.Alloc(DiskGeometry,
GCHandleType.Pinned);
IntPtr pDiskGeometry = PinnedDiskGeometry.AddrOfPinnedObject();

....

// This works

DeviceIoControl(
...,
pDiskGeometry,
(uint) DiskGeometry.Length,
...);

....

PinnedDiskGeometry.Free();

//////////////////
//
// Pinning an allocated DISK_GEOMETRY structure
// and passing via an IntPtr through lpOutBuffer DOES NOT WORK
//
// Why? Is it because structs are allocated on the stack?
//

ie.

[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true,
CharSet = CharSet.Auto)]
private static extern int DeviceIoControl(
IntPtr hDevice, uint dwIoControlCode,
IntPtr lpInBuffer, uint nInBufferSize,
IntPtr lpOutBuffer, uint nOutBufferSize,
out uint lpBytesReturned, IntPtr lpOverlapped);

....

DISK_GEOMETRY DiskGeometry = new DISK_GEOMETRY();
GCHandle PinnedDiskGeometry = GCHandle.Alloc(DiskGeometry,
GCHandleType.Pinned);
IntPtr pDiskGeometry = PinnedDiskGeometry.AddrOfPinnedObject();

....

DeviceIoControl(
...,
pDiskGeometry, // StructLayout sequential, packing = 1
(uint) Marshal.SizeOf(typeof(DISK_GEOMETRY), // 24 bytes
...);

// Call succeeds but DiskGeometry is not updated. WHY???

....

PinnedDiskGeometry.Free();

Cheers,

Steve

May 15 '06 #1
2 7892
> // Call succeeds but DiskGeometry is not updated. WHY???

If DISK_GEOMETRY is declared as a struct, you'll end up pinning a
boxed copy in the GCHandle.Alloc call. That copy will get modified,
not the original DiskGeometry instance.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
May 15 '06 #2
Ahhhh.. caught by value sematics again

Thanks,

Steve

"Mattias Sjögren" wrote:
// Call succeeds but DiskGeometry is not updated. WHY???


If DISK_GEOMETRY is declared as a struct, you'll end up pinning a
boxed copy in the GCHandle.Alloc call. That copy will get modified,
not the original DiskGeometry instance.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

May 15 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Ted Miller | last post by:
Hi folks, I've got an unmanaged routine I'm pinvoking to. It takes a pointer to an array of 3 pointers to bytes, typed as byte**. public static extern void foo(byte **p3pb); unsafe {...
4
by: TT (Tom Tempelaere) | last post by:
Hi people I am wrapping a C dll using PInvoke from C#. I need to wrap the following signature in C int dma_start( const UCHAR* data, UINT data_length ) The function should start with a DMA...
8
by: promko | last post by:
Hi! I need to call the following unmanged method: HFCI __cdecl FCICreate( void FAR* pv) I have written the next managed declaration: public static extern IntPtr FCICreate( IntPtr pv );
4
by: Sai Kit Tong | last post by:
I have to interface managed application with my legacy dll. I have employed the wrapper approach but I have to deal with the asynchronous callback from the legacy dll, which likely goes through a...
3
by: Hexar Anderson | last post by:
I have two questions: a) From documentation located at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcmxspec/html/vcManagedExtensionsSpec_7_7.asp, it says, "Pinning a...
0
by: jim4u | last post by:
I am porting a vb library to vb.net. The vb library has an external call to an unmanaged dll. Existing code: //External function declaration Private Declare Function Uncompress& Lib...
0
by: jim4u | last post by:
I am porting a vb library to vb.net. The vb library has an external call to an unmanaged dll. Existing code: //External function declaration Private Declare Function Uncompress& Lib...
5
by: _iycrd | last post by:
After numerous problems, I'm having second thoughts about using C++/CLI to wrap a native DLL. On the other hand, PInvoke seems like it will take a huge amount of work, if it will work at all. ...
0
by: mike1reynolds | last post by:
I am calling legacy Btrieve database functions using StructureToPtr and PtrToStructure, but I think that I am getting memory corruption from improper marshalling, and I am unclear about when memory...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.