Search code examples
c#pinvokemanaged

How to get integer value from IntPtr-parameter in managed delegate that is called from native function with void *?


I have native function

void SetValue(char *FieldName, void *pValue);

and I want to change it to call earlier set callback/delegate

that has signature

void SetValueDelegate(string fieldName, IntPtr value);

I call native SetValue like this:

int IntValue = 0;
SetValue("MyField", &IntValue);

Now i thought that I can just cast it in managed delegate:

void SetValueDelegate(string fieldName, IntPtr value)
{
    if (fieldName == "MyField")
    {
        int intValue = (int)value;
    }
}

this is not working. If cast to long it's value is 204790096.

How this should be done?


Solution

  • In your managed code, value is the address of the int variable. Therefore, you read that variable like this:

    int intValue = Marshal.ReadInt32(value);
    

    Your code is simply reading the address, rather than the value stored at that address.