日期:2014-05-19  浏览次数:20757 次

C# 调用VC dll 时的指针传递与内存分配问题?
现在我有一个vc写成的dll,其中有一个函数是          
bool   GetPiece(unsigned   char   **   ptr)

这个函数对ptr分配内存,并向分配的内存中写一些数据,然后返回。

外部程序取回这些数据后,释放内存。也就是说ptr的内存申请在GetPiece中,而释放在GetPiece外。

我如何在C#中使用这个函数,向其中传一个指针,并正确返回数据呢?




------解决方案--------------------
public byte [] data;

public unsafe void XXX()
{
fixed(byte * a = &data[0])
{
ddd = abc (a);
}
}
------解决方案--------------------
C#也是可以用指针,不过是不安全的.
------解决方案--------------------
请看看这段代码

fixed(byte * bb = &fingerbmp[0])
{
byte[] ch = new byte[255];
fixed(byte * cc = &ch[0])
{
ii = GetCharacter(0,bb,cc);
Class1.bcha1 = ch;
byte[] ch1 = Class1.bcha;
fixed(byte * dd = &ch1[0])
{
ii = Match2Finger(0,cc,dd,1,3);
byte[] t = new byte[512];
fixed(byte * tmp = &t[0])
{
ii = GetTemplate(0,cc,dd,tmp);
MessageBox.Show(t.ToString());
}
}
}

难道一个fixed里面只能写一个指针变量?难道非要写成这样?难道不能写成fixed(……,……,……)?

初学者,不要笑我,给我出个主意。


unsafe fixed(byte * cc = &ch[0], tmp = &t[0])

You can initialize multiple pointers, as long as they are all of the same type:

fixed (byte* ps = srcarray, pd = dstarray) {...}
To initialize pointers of different type, simply nest fixed statements:

fixed (int* p1 = &p.x)
fixed (double* p2 = &array[5])
// do something with p1 and p2


// SDK上这么写

------解决方案--------------------
use out IntPtr

how is the memory allocated in your C++ code?

1. see
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_20932459.html?qid=20932459

he is adding a function in C++ to release the memory

2. if you use LocalAlloc(), then you can use Marshal.FreeHGlobal in System.Runtime.InteropServices, if you are using CoTaskMemAlloc() in C++, then free it with Marshal.FreeCoTaskMem(), see

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1145286&SiteID=1