gpt4 book ai didi

c# - 从 C# 线程调用非托管代码

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:35:31 25 4
gpt4 key购买 nike

我有一个非托管 C++ 库,我为其创建了一个托管 C++ 包装器。我现在正试图从 C# 中调用它。到目前为止,一切都很好。但是,当我尝试在 C# 线程中调用相同的代码时,我从非托管代码中得到了异常:

表达式: vector 下标超出范围

这可能吗?我假设每个线程都会获得它自己的非托管类实例?

我长期努力地搜索有关从线程内调用非托管代码的更多信息,但至少可以说信息似乎很少。

在此先感谢您的帮助

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#线程启动

Thread t1 = new Thread(DcThread);
t1.Start();

最佳答案

.NET 中的托管类型遵循相同的规则,无论它们是用 C# 还是 C++/CLI 编写的。

虽然可以为每个线程创建 C++/CLI 类的新实例,但如果您不告诉编译器您想要什么,它不会自动发生。

编辑:查看代码,除了内存泄漏外,我没有发现任何问题。 C++/CLI 类应该同时具有析构函数和终结器,如下所示:

!EllipseFit() 
{
delete _unmanagedEllipseFit;
_unmanagedElipseFit = nullptr;
}


~EllipseFit() { this->!EllipseFit(); }

至于崩溃——也许非托管代码使用静态或全局变量,因此不能从多个线程并发使用。

关于c# - 从 C# 线程调用非托管代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5130134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com