我有一個非託管C++庫,爲此我創建了一個託管C++包裝器。我現在試圖從C#中調用它。到現在爲止還挺好。然而,當我試圖從內C#的線程我得到的例外來自非託管代碼中調用相同的代碼:從C#線程調用非託管代碼
表達:向量下標越界
這甚至可能嗎?我假設每個線程都會得到它自己的非託管類的實例?
我已經搜索了很長時間,很難找到更多關於從線程中調用非託管代碼的信息,但是信息似乎至少說明了一點。
預先感謝任何幫助
C++包裝
// Managed wrapper
public ref class EllipseFit
{
private:
// Pointer to unmanaged class
UnmanagedEllipseFit* _unmanagedEllipseFit;
public:
// Constructor & Destructor
EllipseFit()
{
_unmanagedEllipseFit = new UnmanagedEllipseFit();
}
~EllipseFit()
{
delete _unmanagedEllipseFit;
}
List<Ellipse^>^ ProcessImage(array<Byte>^ image, int width, int height)
{
pin_ptr<unsigned char> pimg = &image[0];
_unmanagedEllipseFit->processsImage(pimg, width, height);
// Marshal the results... <edited>
return ellipses;
}
};
C#線程
private void DcThread()
{
EllipseFit ellipseFit = new EllipseFit();
string fullPath = _fileList.GetNext();
while (fullPath != null)
{
// Load the image
Bitmap bitmap = new Bitmap(fullPath);
byte[] imageData = TsImage.ConvertBitmap(bitmap);
// Process
List<DcEllipse> ellipses = ellipseFit.ProcessImage(imageData, bitmap.Width, bitmap.Height);
// Save the associated text file.. (Debug)
TextWriter textFile = new StreamWriter(fullPath.Replace(".jpg", ".txt"));
foreach (DcEllipse ellipse in ellipses)
textFile.WriteLine(String.Format("{0} {1} {2} {3} {4}", ellipse.X, ellipse.Y, ellipse.MajorAxisLength, ellipse.MinorAxisLength, ellipse.Angle));
textFile.Close();
fullPath = _fileList.GetNext();
}
}
C#線程啓動在.NET
Thread t1 = new Thread(DcThread);
t1.Start();
你將不得不表現出一定的C++/CLI代碼爲我們做任何這種感覺。 – 2011-02-26 22:26:22
*編輯*只有當我有多個線程時纔會出現異常。在它的一個線程中,自己沒有其他線程,我沒有看到任何異常。 – 2011-02-26 22:31:48
您是否爲每個線程顯式創建類的單獨實例?當它們不是爲多線程而設計時,共享託管包裝類或非託管本機類是一個很大的禁忌。 – 2011-02-26 22:35:34