I’m trying to convert a C# delegate to a C++ function pointer, using Managed C++. Here’s the method we were previously using:
// Define a delegate
public delegate void ADelegate(Int32);
ADelegate^ delegateInstance;
// Define a function pointer
typedef void (__stdcall *AFuntionPointer)(int);
AFuntionPointer functionPointerInstance;
// Create an instance of a delegate, using GetFunctionPointerForDelegate
delegateInstance = gcnew ADelegate(this, &AClass::AFunction);
// Convert the delegate to a pointer
IntPtr anIntPtr = Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(delegateInstance);
// Cast the pointer into a function pointer
functionPointerInstance = static_cast<AFuntionPointer>(anIntPtr.ToPointer());
If I turn the ADelegate‘s parameter from an Int32 to a String^, to what type should I change the AFunctionPointer‘s parameter to? In another words, if I changed the first two lines in the above code to:
public delegate void ADelegate(String ^);
ADelegate^ delegateInstance;
How should I change the next two lines?
// To what type does GetFunctionPointerForDelegate translate String^ to?
typedef void (__stdcall *AFuntionPointer)( /* char*? std::string? */ );
AFuntionPointer functionPointerInstance;
Marshal::GetFunctionPointerForDelegate() on that delegate would generate a function pointer that’s compatible with
String^marshals toconst char*unless a [MarshalAs] attribute is applied to the delegate argument. Marshaling directly to std::string is not possible, the pinvoke marshaller doesn’t know anything about C++ object layout for classes that are declared in a header file.