Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 991
char m Avatar asked Dec 18 '22 16:12

char m


1 Answers

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.

like image 164
David Heffernan Avatar answered Jan 28 '23 19:01

David Heffernan