如何将C++ dll 在 C# 窗口窗体应用程序下的工作线程中运行

How to put C++ dll running in Worker Thread under C# Window Form application

本文关键字:应用程序 工作 线程 运行 窗体 窗口 C++ dll      更新时间:2023-10-16

我喜欢在工作线程下运行C++dll,以便C#应用程序的窗口窗体(窗体上的那些按钮(仍然可用。现在,一旦 dll 正在运行,就无法单击 C# 应用程序中 Windows 窗体上的按钮。

我C++导出了成员函数的类。

class Soln {
public:
      //Export functions
      Soln();
      ~Soln();
       voidgetObjectInformation(void);
       void setProcessOver(void);
};
/************These export funcitons are created*********/
extern "C"
{
    __declspec(dllexport) Soln* Soln_Create() {
        return new Soln();
    }
    __declspec(dllexport) void Soln_getObjectInformation(Soln* bsn) {
        return bsn->getObjectInformation();
    }
    __declspec(dllexport) void Soln_setProcessOver(Soln* bsn) {
        bsn->setProcessOver();
        return;
    }
    __declspec(dllexport) void Soln_delSoln(Soln* bsn) {
        bsn->~Soln();
        return;
    }
}

在 C# 中,它使用 PInvoke 进行接口。

    public partial class Form1 : Form
    {
        [DllImport("Soln_Cpp_Dll.dll", EntryPoint = "Soln_Create")]
        public static extern IntPtr Soln_Create();
        [DllImport("Soln_Cpp_Dll.dll", EntryPoint = "Soln_delSoln")]
        public static extern void Soln_delSoln(IntPtr bsn);
        [DllImport("Soln_Cpp_Dll.dll", EntryPoint = "Soln_getObjectInformation")]
        public static extern IntPtr Soln_getObjectInformation(IntPtr bsn);
        [DllImport("Soln_Cpp_Dll.dll", EntryPoint = "Soln_setProcessOver")]
        public static extern void Soln_setProcessOver(IntPtr bsn);
        //Variables
        IntPtr Soln;
        public Form1()
        {
           InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
           Soln = Soln_Create();
        }
        private void button4_Click(object sender, EventArgs e)
        {
           Soln_delBaggageSoln(Soln);
        }
     }

现在的问题是一旦dll运行,我就无法单击按钮4停止。

我搜索并发现我可以在 C# 中创建一个工作线程。

Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));

但这只是创建一个新对象,因为我期待一个返回IntPtr Soln,如何在工作线程下运行 dll?

若要解决您的问题,请在单击按钮时在 c# 中触发任务并忘记它。

Task.Factory.StartNew(() => Soln_delBaggageSoln(Soln)); //for example

这样,当 dll 函数运行时,您的 UI 线程不会被阻止,因为它会在其他线程中运行。

相关文章: