none
Asynchronous communication between C++ and C# RRS feed

  • Question

  • I have a console application in C++ that when loaded load a library in C#, which, in turn, when loaded shows a modal form with several buttons.

    I need to implement a call back function from C# to C++ to indicate, in the C++ console output, every time an action is made in the modal form.

    I have treated the following code C++:

    #include "pch.h"
    #include <iostream>
    #include <Windows.h>
    #include <string>
    #include <tchar.h>
    #import ".\CSharpDll.tlb" raw_interfaces_only
    
    int wmain(int argc, char* argv[]) {
    	CoInitialize(0); // Init COM
    
    	BSTR thing_to_send = ::SysAllocString(L"10 20");
    	BSTR returned_thing;
    	CSharpDll::_TheClassPtr obj(__uuidof(CSharpDll::TheClass));
    	HRESULT hResult = obj->GetTheThing(thing_to_send, &returned_thing);
    
    	if (hResult == S_OK) {
    		std::wcout << returned_thing << std::endl;
    		return 0;
    	}
    	return 1;
    }
    //Call back function to test
    typedef void(*CallbackFunction)(const char*);
    void setCallback(CallbackFunction delegate)
    {
    	std::cout << &delegate << std::endl;
    }

    La aplicacion anterior se comunica con la libreria en C# con el siguiente codigo C#:

    using System;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    using System.Runtime.CompilerServices;
    using System.Threading.Tasks;
    using System.IO.Pipes;
    using System.IO;
    using System.Text;
    
    namespace BimObjectCSharpClass
    {
        public class SendData
        {
            public delegate void CallbackDelegate(string message);
            [MethodImplAttribute(MethodImplOptions.InternalCall)]
            public static extern void SetCallback(IntPtr aCallback);
            private CallbackDelegate del;
    
            public void TestCallbacks()
            {
                System.Console.Write("Registering C# callback...\n");
                del = new CallbackDelegate(Callback01);
                SetCallback(Marshal.GetFunctionPointerForDelegate(del));
    
                System.Console.Write("Calling passed C++ callback...\n");
            }
    
            public void Callback01(string message)
            {
                System.Console.Write("callback 01 called. Message: " + message + "\n");
            }
    
        }
    
        [ComVisible(true)] // Don't forget 
        [ClassInterface(ClassInterfaceType.AutoDual)] // these two lines
        [Guid("485B98AF-53D4-4148-B2BD-CC3920BF0ADF")] // or this GUID
        public class TheClass
        {
            int Num1;
            int Num2;
            public String GetTheThing(String arg) // Make sure this is public
            {
                string s = arg;
                string[] words = s.Split(' ');
    
                Num1 = Int32.Parse(words[0]);
                Num2 = Int32.Parse(words[1]);
                ShowForm(Num1, Num2);
                int retVal = 0;
                return retVal.ToString();// arg + "the thing";
            }
    
            static void ShowForm(int a, int b)
            {
                Form Form4 = new Form1(a, b);
                Form4.ShowDialog();
            }
        }
    }

    When the C ++ application is executed, the form is not displayed and the application ends without an answer after a few seconds (15 mm).

    If the section indicated as //Return call function statement is commented (on C# side), the application is executed and the form is displayed. This indicates that something is not declared as it should be on the C# side.

    For me it is totally new to make C++ converge with C# during a modal function like that of the form.

    I need to know how to correct the statement so that the callback function is recognized.




    • Edited by Fisad Saturday, November 17, 2018 4:10 PM
    Friday, November 16, 2018 1:44 PM

All replies

  • In the code you have posted, the C# is calling SetCallback, but the C++ function is setCallback.  Those are two different things.


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Friday, November 16, 2018 10:42 PM
  • in this case it is irrelevant since the C # code is never loaded, something in the position of the statement is bad
    Saturday, November 17, 2018 9:08 AM
  • If the form is shown when you comment some lines out, you may get a not shown exception if the lines are not commented. Can you add eg a messagebox to show exceptions?
    Saturday, November 17, 2018 11:13 AM
  • I have corrected the code but when I run the callback function it gives me an ECall security error
    Saturday, November 17, 2018 4:08 PM
  • Hi Fisad,

    Could you please share the detailed error message, and complete sample code and steps to reproduce the issue.

    Best regards,

    Zhanglong 


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, November 19, 2018 7:04 AM
    Moderator