将状态更新从C 中的功能发送到C#

send status updates from function in C++ to C#

本文关键字:功能 状态 更新      更新时间:2023-10-16

我在C DLL中具有很大的功能,可以执行许多任务。我们从C#包装器称呼它,并且C 功能要完成约20秒。我想改变我们运行它的方式。我的想法是1.调用C 函数异步和2.每次完成C 功能的任务完成时,我想将" Task1已完成"消息发送到C#功能并将其显示给用户,以便他们知道后台发生了什么。

有什么想法如何执行?我抬头看了几个例子,但感到困惑。我想知道是否有人这样做。寻找一些指针。

ex:C 代码

int  CppLibrary::ExecuteWorkflow( param1,param2, param3,param4,param5)
{
task1;
task2;
task3;
task4;
task5;
}
calling the C++ function from C# wrapper:
[DllImport(_dllLocation)]
public static extern int ExecuteWorkflow( param1,param2, param3,param4,param5);

您可以使用C#中的代表来调用您的C 包装器,然后根据您的情况使用"调用"或" beginInvoke"。

dispatcher.begininvoke方法

  1. 使用c like名称(导出" c" __declspec(dllexport))
  2. 导出您的C 功能
  3. 使用dllimport为您的库呼叫创建dllimport。
  4. 创建一个线程并使用您的回调逻辑调用导入(即任务。与委托)。

这是P/Indoke C 函数的包装类别。希望可以帮助您。

class CSUnmangedTestClass : IDisposable
{
    #region P/Invokes
    [DllImport(@"E:VS2012TeststestDebugDllImport.dll", EntryPoint="#1")]
    private static extern IntPtr Foo_Create();
    [DllImport(@"E:VS2012TeststestDebugDllImport.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern int Foo_Bar(IntPtr pFoo);
    [DllImport(@"E:VS2012TeststestDebugDllImport.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern void Foo_Delete(IntPtr pFoo);
    #endregion
    #region Members
    // variable to hold the C++ class's this pointer
    private IntPtr m_pNativeObject;
    #endregion
    public CSUnmangedTestClass()
    {
        this.m_pNativeObject = Foo_Create();
    }
    public void Dispose()
    {
        Dispose(true);
    }
    protected virtual void Dispose(bool bDisposing)
    {
        if (this.m_pNativeObject != IntPtr.Zero)
        {
            Foo_Delete(m_pNativeObject);
            this.m_pNativeObject = IntPtr.Zero;
        }
        if (bDisposing)
        {
            // No need to call the finalizer since we've now cleaned up the unmanged memory
            GC.SuppressFinalize(this);
        }
    }
    ~CSUnmangedTestClass()
    {
        Dispose(false);
    }
    #region Wrapper methods
    public int Bar()
    {
        return Foo_Bar(m_pNativeObject);
    }
    #endregion
}