I\'m trying to do something very similar to this but I\'m struggling to pass the string to/from the callback.
This is a pared down version of the code I\'m trying to run
Solved it with a bit of experimentation and some more detailed examination of the docs on different forms of bind.
This is the resulting code which works as expected:
using namespace System;
using namespace System::Runtime::InteropServices;
#pragma unmanaged
// The unmanaged boost function prototype the native library wants to bind to
typedef boost::function<std::string(const std::string&)> MyNativeCallback;
// The unmanaged library I'm trying to wrap
class MyUnmanagedClass
{
public:
MyUnmanagedClass() {}
void RegisterCallback(MyNativeCallback callback);
};
typedef std::string(__stdcall *ChangeCallback)(std::string);
public delegate std::string ChangeHandler(std::string);
#pragma managed
// The managed callback we'll eventually trigger if all this works.
public delegate std::string ManagedHandler(const std::string&);
// A managed wrapper to bridge the gap and provide a managed call in response to the unmanaged callback
public ref class MyManagedClass
{
protected:
MyUnmanagedClass* m_responder;
public:
event ManagedHandler^ OnChange;
public:
MyManagedClass():
m_responder(new MyUnmanagedClass())
{
// Example code I'm trying to adapt from here: http://stackoverflow.com/questions/163757/how-to-use-boostbind-in-c-cli-to-bind-a-member-of-a-managed-class
ChangeHandler^ handler = gcnew ChangeHandler(this, &MyManagedClass::HandleRequest);
GCHandle gch = GCHandle::Alloc(handler);
System::IntPtr ip = Marshal::GetFunctionPointerForDelegate(handler);
ChangeCallback cbFunc = static_cast<ChangeCallback>(ip.ToPointer());
MyNativeCallback handlerToBind = boost::bind<std::string>(cbFunc, _1);
m_responder->RegisterCallback(handlerToBind);
}
std::string HandleRequest(const std::string& s)
{
return OnChange(s);
}
};