Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6676719
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T04:01:39+00:00 2026-05-26T04:01:39+00:00

I’m wondering about the proper way of allocating memory to a pointer (C/C++ style)

  • 0

I’m wondering about the proper way of allocating memory to a pointer (C/C++ style) from within C#. Then, holding onto that memory for an extended period of time. Also, this allocated memory is meant to be used for calls to DeviceIoControl(). Consider this class:

class Example {
    const uint memCommit = 0x1000;
    const uint pgReadWrite = 0x04;

    [DllImport("Kernel32.dll", SetLastError = true)]
    public static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, uint flAllocationType, uint flProtect);

    [StructLayout(LayoutKind.Sequential)]
    struct AStruct {
        uint val1;
        uint val2;
        uint val3;
    }

    private static unsafe AStruct* pStruct = (AStruct*)VirtualAlloc(IntPtr.Zero, (UIntPtr)(sizeof(AStruct)), memCommit, pgReadWrite).ToPointer();


    public static unsafe void ReadFromDevice() {
        // setup the structure for the IOCTL call
        pStruct->val1 = 70; //
        pStruct->val2 = 0;
        pStruct->val3 = 0x0f;

        // call P/Invoked DeviceIoControl() here with pStruct as both the in/out pointers

        // check that all is well
    }
}

This whole thing doesn’t “feel” right to me, but I’ve learned enough over the years to not immediately question implementation without studying it. That’s what brings me to this forum. I’m seeing behavior I’ve never seen before.

Using the debugger, I place a break point at the point the pointer is instantiated with the call to VirtualAlloc(). I make note of the address that’s given to me (for example, 0x03bf78cc). I also have a break point placed at another function which calls the method, ReadFromDevice(), above. As I step through ReadFromDevice(), I notice that pStruct contains a different address than the one that was allocated when the program first began. The value of pStruct has changed from my number above to, let’s say, 0x03cd9004.

I’ve worked with calling into the Kernel32 function DeviceIoControl() before and the method used there was to instantiate a pinned GCHandle to the data structure being used in the call to DeviceIoControl(), make the call, copy out the appropriate data and then free the handle. This approach seems less error prone and keeps in consistency with the model of allocating and freeing unmanaged memory as quickly as possible.

As I mentioned, the approach used in the code I’m into now just doesn’t “feel” right, but I’m not sure about why. I’ve turned up nothing with searches on Google for things like “c sharp memory address changed after alloc” and so forth. Should this approach be changed? (In the past, I’ve used pinned GC Handles.) Is the above approach sound? Regardless, why would the pointer say one memory address during program startup and then another when the ReadFromDevice() call is actually performed? As I write this post, I’m wondering if the change in address is as “odd” as I first thought. Nevertheless, I’m still questioning this use of pointers. Please advise.

Thanks,
Andy

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T04:01:40+00:00Added an answer on May 26, 2026 at 4:01 am

    This is not necessary, you can leave it up to the pinvoke marshaller to do the right thing. Simply provide overloads of the function to pass the arguments, customized to fit the call. For example:

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

    And you’d call it like this:

    AStruct result;
    uint resultSize = Marshal.SizeOf(result);
    uint bytesReturned;
    bool okay = DeviceIoControl(hDev, somecode, IntPtr.Zero, 0, 
                   out result, resultSize,
                   out bytesReturned, IntPtr.Zero);
    if (!okay) throw new Win32Exception();
    System.Diagnostic.Debug.Assert(bytesReturned == resultSize);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I am reading a book about Javascript and jQuery and using one of the
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.