Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does GetFunctionPointerForDelegate convert a String^ parameter in a delegate into?

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;
like image 257
Japtar Avatar asked May 28 '26 20:05

Japtar


1 Answers

Marshal::GetFunctionPointerForDelegate() on that delegate would generate a function pointer that's compatible with

  typedef void (__stdcall *AFuntionPointer)( const char* );

String^ marshals to const 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.

like image 99
Hans Passant Avatar answered May 31 '26 11:05

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!