I'll fiddle with it, I was getting a linking error. I was using
something similar to this
msclr::auto_gcroot<ManagedReceiver^receiver;
and as soon as I threw static in front it was not happy.
On another note, I've found a different solution to the problem and I
was hoping you could help explain exactly what is going on.
So, my problem is that I have a native class that needs to
communicate, via callbacks, asynchronously to a managed C++/CLI class,
which then communicates to C#.
Originally with MC++ we were using the bridge class, and now that
we've moved, or are moving to CLI we need to find a different
approach. So while I was fiddling, I did this. I just included a
seperate function outside of the managed class in a seperate
namespace. And it uses the managed class static reference to itself
to invoke it's callbacks, and it works. But why has no one mentioned
this before? It's the best solution I;ve seen yet, what's wrong with
it? Here's some code.
namespace ManagedLib
{
[StructLayout(LayoutKind::Sequential, CharSet=CharSet::Ansi, Pack=8)]
public ref struct MStruct
{
public:
System::Int32 x;
System::Int32 y;
[MarshalAs(UnmanagedType::ByValTStr, SizeConst=50)]
System::String^ str;
virtual String^ ToString() override
{
return String::Format("X:{0} Y:{1} STR:
{2}",Convert::ToString(x),Convert::ToString(y),str );
}
};
public delegate void DataChangedEventHandler(MStruct^ item);
public ref class MClass
{
private:
UnmanagedLib::UClass* pUnmanagedClass_ ;
public:
MClass()
{
pUnmanagedClass_ = new UClass(); //unmanaged heap
//pUnmanagedClass_-
>RegisterUnmanagedCallBack(&(_UClassBridge::Unmana gedBridgeCallback));
pUnmanagedClass_-
>RegisterUnmanagedCallBack(&(UnmanagedCallbackMeth ods::UnmanagedBridgeCallback));
pMe_ = this;
}
~MClass(){
delete pUnmanagedClass_;
};
static MClass^ pMe_ = nullptr;
DataChangedEventHandler^ pManagedDelegate_;
void RunSimulation()
{
MStruct^ item = gcnew MStruct();
item->x = 1;
item->y = 2;
item->str = "Test";
for(int i = 0;i< 100000;i++)
{
item->x = i+1;
UStruct uItem;
Marshal::StructureToPtr(item, (System::IntPtr)&uItem, true);
pUnmanagedClass_->FireUnmanagedCallback(uItem);
Thread::Sleep(100);
}
}
};
}
namespace UnmanagedCallbackMethods
{
static void UnmanagedBridgeCallback(const UStruct item)
{
Console::WriteLine("UnmanagedBridgeCallback: Fired");
UStruct uItem = item;
ManagedLib::MStruct^ mItem = gcnew ManagedLib::MStruct();
Marshal::PtrToStructure((System::IntPtr)&uItem, mItem);
ManagedLib::MClass::pMe_->pManagedDelegate_->Invoke(mItem);
}
};
Thanks again for all the help.