0

I have unmanaged C++ DLL (MFC Extension DLL to be precise). This DLL loads the C# DLL and calls its method Start() as shown below. All this works.

C++ ==============================================

BOOL CForwarder::Start()
{
    return InitMyManagedFlex();
}



// CForwarder member functions
BOOL CForwarder::InitMyManagedFlex()
{
    // Initialize COM.
    HRESULT hr = CoInitialize(NULL);

    // Create the interface pointer.
    IForwarderPtr pIFwd(__uuidof(MyForwarder));

    long lResult = 0;
    VARIANT_BOOL ret = FALSE;
    BSTR bstr = AsciiToBSTR("AAA");

    // Call the Add method.
    pIFwd->Start(bstr, &ret);

    SysFreeString(bstr);

    wprintf(L"The result is %d\n", ret);

    // Uninitialize COM.
    CoUninitialize();

    return (ret == VARIANT_TRUE) ? TRUE : FALSE;
}


// Interface declaration.
public interface IForwarder
{
    bool StartCmd(string msg);
};

==================================================================

The C# class in C# DLL looks like this:

namespace MyManagedFlex
{

    public class MyForwarder:IForwarder
    {
        public bool StartCmd(string msg)
        {
            return StartSending();
        }

        private bool StartSending()
        {
            return true;
        }
    }

    // Interface declaration.
    public interface IForwarder
    {
        bool StartCmd(string msg);
    };

}

Here is the basic question: How do I pass a callback function in Start() and how and what I implement in C++ and C# so that C# could call back C++ DLL at any time it desires and pass some parameters.

Leon Havin
  • 177
  • 2
  • 14
  • You need a delegate. See : https://stackoverflow.com/questions/5250478/c-sharp-marshalled-callbacks – jdweng Nov 24 '17 at 00:57
  • Since you are using COM, it makes sense for you to implement a COM interface and pass that to the C# code. – David Heffernan Nov 24 '17 at 09:55
  • @jdweng That question discusses the reverse problem. There the asker is defining the callback in C# code, and passing a delegate to the C code. In this question, the asker wants to define the callback in the C++ code and pass that function pointer to the C# code. In the question you link to, the C# process is the executable, linking to the unmanaged C DLL via pinvoke. But in this question the C++ MFC DLL hosts the C# assembly using COM to load that C# assembly. – David Heffernan Nov 24 '17 at 11:15
  • David, your last comment is correct, but I stilldon't have a solution. I tried to define this in Forwarder.cpp class: typedef void(*functionPointer)(const char* data); functionPointer myFunc; // This is the actual function that is called from C# DLL (such as MyManagedFlex.dll) void CForwarder::CallbackFromCSharp(const char* data) { TRACE(data); } Then I tried to call inside InitMyManagedFlex myFunc = &CallbackFromCSharp; pIFwd->Start(bstr, myFunc, &ret); But the last 2 lines won't compile... – Leon Havin Nov 24 '17 at 23:14

0 Answers0