Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8425473
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T04:16:47+00:00 2026-06-10T04:16:47+00:00

In my Visual Studio solution I have UI implemented in C# and some code

  • 0

In my Visual Studio solution I have UI implemented in C# and some code implemented in native C++.

I use BackgroundWorker class to implemenent reporting progress of execution long operation.

How can I use BackgroundWorker to report progress from my native C++ code?

In other words, how can I rewrite the C# code below to native C++ and call obtained C++ code from C#?
If it is not possible to rewrite the code below directly, it could be good to know about other equivalent solutions. Thanks.

class MyClass 
{
    public void Calculate(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        for (int i = 0; i < StepCount; i++)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
                break;
            }

            // code which handles current iteration here

            worker.ReportProgress((i + 1) * 100 / StepCount, 
                "Report progress message");
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T04:16:48+00:00Added an answer on June 10, 2026 at 4:16 am

    Example follows.
    It was tested on x86 C# and native Visual C++:

    CppLayer.h:

        #ifdef CPPLAYER_EXPORTS
        #define CPPLAYER_API __declspec(dllexport)
        #else
        #define CPPLAYER_API __declspec(dllimport)
        #endif
    
        extern "C" {
            typedef void (__stdcall *ReportProgressCallback)(int, char *);
            typedef bool (__stdcall *CancellationPendingCallback)();
    
            struct CPPLAYER_API WorkProgressInteropNegotiator 
            {
                ReportProgressCallback progressCallback;
                CancellationPendingCallback cancellationPending;
                bool cancel;
            };
    
            CPPLAYER_API void __stdcall CppLongFunction(WorkProgressInteropNegotiator& negotiator);
        }
    

    CppLayer.cpp:

    #include "stdafx.h"
    #include "CppLayer.h"
    
    #include <iostream>
    
    extern "C"
    {
        // This is an example of an exported function.
        CPPLAYER_API void __stdcall CppLongFunction(WorkProgressInteropNegotiator& negotiator)
        {
            const int STEP_COUNT = 12;
    
            char * messages[3] = {"ONE", "TWO", "THREE"};
    
            for (int i = 0; i < STEP_COUNT; i++)
            {
                Sleep(100);
    
                if (negotiator.cancellationPending()) {
                    negotiator.cancel = true; 
                    break;
                }
    
                std::cout << "Calculate " << i << std::endl;
                negotiator.progressCallback((i + 1) * 100 / STEP_COUNT, messages[i % 3]);
            }
        }
    
    };
    

    C# class which interoperate with C++ code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using System.Threading;
    
    namespace CSharpLayer
    {
        class SandboxCppProgress
        {
            public delegate void ReportProgressCallback(int percentage, string message);
    
            public delegate bool CancellationPendingCallback();
    
            [StructLayout(LayoutKind.Sequential)]
            public class WorkProgressInteropNegotiator
            {
                public ReportProgressCallback reportProgress;
                public CancellationPendingCallback cancellationPending;
    
    #pragma warning disable 0649
                // C# does not see this member is set up in native code, we disable warning to avoid it.
                public bool cancel;
    #pragma warning restore 0649
            }
    
            [DllImport("CppLayer.dll")]
            public static extern void CppLongFunction([In, Out] WorkProgressInteropNegotiator negotiator);
    
            static void CSharpLongFunctionWrapper(object sender, DoWorkEventArgs e)
            {
                BackgroundWorker bw = sender as BackgroundWorker;
    
                WorkProgressInteropNegotiator negotiator = new WorkProgressInteropNegotiator();
    
                negotiator.reportProgress = new ReportProgressCallback(bw.ReportProgress);
                negotiator.cancellationPending = new CancellationPendingCallback(() => bw.CancellationPending);
    
                // Refer for details to
                // "How to: Marshal Callbacks and Delegates Using C++ Interop" 
                // http://msdn.microsoft.com/en-us/library/367eeye0%28v=vs.100%29.aspx
                GCHandle gch = GCHandle.Alloc(negotiator);
    
                CppLongFunction(negotiator);
    
                gch.Free();
    
                e.Cancel = negotiator.cancel;
            }
    
            static EventWaitHandle resetEvent = null;
    
            static void CSharpReportProgressStatus(object sender, ProgressChangedEventArgs e)
            {
                string message = e.UserState as string;
                Console.WriteLine("Report {0:00}% with message '{1}'", e.ProgressPercentage, message);
    
                BackgroundWorker bw = sender as BackgroundWorker;
                if (e.ProgressPercentage > 50)
                    bw.CancelAsync();
            }
    
            static void CSharpReportComplete(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled)
                {
                    Console.WriteLine("Long operation canceled!");
                }
                else if (e.Error != null)
                {
                    Console.WriteLine("Long operation error: {0}", e.Error.Message);
                }
                else
                {
                    Console.WriteLine("Long operation complete!");
                }
                resetEvent.Set();
            }
    
            public static void Main(string[] args)
            {
                BackgroundWorker bw = new BackgroundWorker();
                bw.WorkerReportsProgress = true;
                bw.WorkerSupportsCancellation = true;
                bw.ProgressChanged += CSharpReportProgressStatus;
                bw.DoWork += CSharpLongFunctionWrapper;
                bw.RunWorkerCompleted += CSharpReportComplete;
    
                resetEvent = new AutoResetEvent(false);
    
                bw.RunWorkerAsync();
    
                resetEvent.WaitOne();
            }
        }
    }
    

    Following links might be useful:

    • Interop with Native Libraries (Mono)
    • How to: Marshal Callbacks and Delegates Using C++ Interop
    • How to: Marshal Function Pointers Using PInvoke
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Visual Studio 2010 solution that contains a class library (ProjectA) and
I have a Visual Studio solution with two projects : A class library MyLib
Hi I have a Visual Studio solution and an ASP.NET MVC project that uses
I have a Visual Studio solution containing 2 project: main project and test (via
I have a Visual Studio 2010 solution with 5 projects in it, two libraries
We have a Visual Studio 2008 solution under VSS source control. The solution contains
I have a visual studio 2008 solution with multiple c# library projects, a Web
I have a Visual studio 2008 solution, with 2 projects. A DLL, A, and
I have a Visual Studio 2005 solution. Every time I try to run the
I have a Visual Studio 2010 solution that contains multiple projects. One of these

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.