日期:2014-05-17  浏览次数:21433 次

[急切求助]C#如何拷贝内存?
//把data中内容拷贝到byte[] newm数组中
private int funcTest2(ref IntPtr data, ref int retVal)    
{
//下面两行代码,用开发工具编译运行没有问题
//但是直接运行EXE文件会报错误。。。
byte[] newm = new byte[retVal];
Marshal.Copy(data, newm, 0, retVal);

//是不是要通过别的方式来实现内存拷贝???
//GCHandle retPinned = GCHandle.Alloc(ret); 
}

------解决方案--------------------
byte[] newm = new byte[retVal];
int t = 1234;
GCHandle h = GCHandle.Alloc(t, GCHandleType.Pinned);
IntPtr p = h.AddrOfPinnedObject();
Marshal.Copy(p, newm, 0, retVal); 

------解决方案--------------------
funcTest2(ref IntPtr data, ref int retVal)   
参数对应C++原型是unsigned char *&ucData, int *dataLen
感觉你写的有问题 长度是个指针 你不应该直接用指针的值来初始化数组大小byte[] newm = new byte[retVal];

你应该先得到大小dataLen

private int funcTest2(ref IntPtr data, IntPtr  retVal)   
{
int[] dataLen = new int[1];
Marshal.Copy(retVal, dataLen , 0, 1);//先计算dataLen


byte[] newm = new byte[dataLen[0]];
Marshal.Copy(data, newm, 0, dataLen[0]);
}

一点建议 
------解决方案--------------------
错误提示是什么。应该是你调用的问题。
------解决方案--------------------
什么原因造成:已垃圾回收委托进行了回调。
[ 标签:原因,垃圾回收 ] 对“video!MySoftwareStudio.NvsTalk.NvsTalkInterface+M_MessageCallback::Invoke”类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们。 
------解决方案--------------------
引用:
funcTest2(ref IntPtr data, ref int retVal)  
参数对应C++原型是unsigned char *&ucData, int *dataLen
感觉你写的有问题 长度是个指针 你不应该直接用指针的值来初始化数组大小byte[] newm = new byte[retVal];

你应该先得到大小dataLen

private int f……

=========================
之前看C++和C#参数类型对照表:
C++中 int*, 在C#中可以用 ref int来接收。
------解决方案--------------------
同样想了解,帮顶。。。