Writing float value to unmanaged memory?
I am creating a .NET client and I referenced the RCW provided by the OPC Foundation .
One of the functions has this parameter:
[IN] IntPtr pPercentDeadBand
The documentation mentions that I have to pass a pointer to a float value.
This is where I am afraid. I found Marshall..WriteByte, .WriteInt16 and .Writeint32.
But don't write anything float value from managed memory to unmanaged memory.
Instead, you can use Marshal.Copy and pass float [] with a single element.
Or you can write a bit from float to int and use Marshal.WriteInt32. This combined structure can be used to convert between the two
[StructLayout(LayoutKind.Explicit)]
struct SingleInt32Union
{
[FieldOffset(0)]
float s;
[FieldOffset(0)]
int i;
}
source to share
I would do it in one of these ways, ordering from best to worst solution:
-
Modify the definition of the Interop assembly for this method. If it is a pointer to float, it must be declared as follows.
ref float pPercentDeadBand
not
[In] IntPtr pPercentDeadBand
-
Use unsafe code to pass a pointer to float:
unsafe { float theValueToPass = 345.26f; IntPtr thePointer = new IntPtr(&theValueToPass); //pass thePointer to the method; }
-
Allocate 4 bytes of memory using Marshal.AllocHGlobal, copy the float value from the float array of one element using Marshal.Copy, call the method using the pointer obtained from Marshal.AllocHGlobal, and then free the memory by the marshal. FreeHGlobal.
source to share
If it's the OPC Foundation, it looks like they have managed API code . UA SDK 1.00 includes support for the .NET development environment, according to opcconnect.com .
source to share