问题描述
我需要将double数组转换为IntPtr,并将此IntPtr转换为字节数组.
我要进行反转也只是确认存储在字节数组中的值是正确的int数组.
我要执行的步骤是
double [] dmanagedArray = new double [length];
for(int intI = 0; intI< dmanagedArray.Length; intI ++)
{
dmanagedArray [intI] = intI * 10;
}
int大小= Marshal.SizeOf(dmanagedArray [0])* dmanagedArray.Length;
IntPtr srcPtr1 = Marshal.AllocHGlobal(size);
//这会将双精度数组复制到IntPtr.元帅.Copy(dmanagedArray,0,srcPtr1,dmanagedArray.Length);
//现在让我们将此IntPtr转换为字节数组
byte [] byteArray =新的byte [dmanagedArray.Length]
//Marshal.Copy(srcPtr1,byteArray,0,byteArray.Length);
在我的情况下,字节[]现在包含所有值为0的值.
我认为这是错误的.如何进行正确的转换.
Hi,
I have requirement to convert double array to IntPtr and this IntPtr to byte array.
I want to do the reversal also just confirm values stored in byte array is of correct int array.
The steps I am following is
double[] dmanagedArray = new double[length];
for (int intI = 0; intI < dmanagedArray.Length; intI++)
{
dmanagedArray[intI] = intI * 10;
}
int size = Marshal.SizeOf(dmanagedArray[0]) * dmanagedArray.Length;
IntPtr srcPtr1 = Marshal.AllocHGlobal(size);
// This will copy double array to IntPtr.
Marshal.Copy(dmanagedArray, 0, srcPtr1, dmanagedArray.Length);
// Now let's convert this IntPtr to byte array
byte[] byteArray = new byte[dmanagedArray.Length]
//Marshal.Copy(srcPtr1, byteArray, 0, byteArray.Length);
In my case what is happening is , byte[] now contains all the values as 0.
which I think is wrong. How to do right conversion.
推荐答案
顺便说一句,为什么要使用double?如果需要64位整数,请使用 long ;如果需要32位整数,请使用 int (或者更好的是, ulong 和 uint ).使用浮点格式进行指针运算时,由于使用了指数"运算法则,可能会产生意想不到的结果.部分.
Btw, why use double? If you need 64-bit integer you use long, if you need 32-bit integer you useint (or better yet, ulong and uint). Use floating point format for pointer operations using pointer arithmetic can yield unexpected result because of the "exponent" part.
这篇关于将double []转换为IntPtr,然后转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!