Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 338
  • Last Modified:

Convert delegate to function pointer in Visual Studio 2005

Hi,

I'm wondering if there is a way to convert delegates to function pointers in Visual Studio 2005 without making function calls through any DLL nor using the /clr:oldSyntax compiler option?

I have read the following articles, but the example codes are based on the VS2003 syntax:
    http://www.codeproject.com/managedcpp/delegate_to_callback.asp
    http://www.codeproject.com/managedcpp/unmanaged_to_managed.asp

Thanks,

James
0
james567
Asked:
james567
1 Solution
 
lakshman_ceCommented:
Use Marshal::GetFunctionPointerForDelegate

Here is the sample code

#include "stdafx.h"

using namespace System;
using namespace System::Runtime::InteropServices;
delegate void myMethodDelegate( // Declares a delegate for a method that takes in an int and returns a String.
int myInt );
typedef void (*PFUNC)(Int32);

// Defines some methods to which the delegate can point.
ref class mySampleClass
{
public:

   // Defines an instance method.
   void myStringMethod( int myInt )
   {
      if ( myInt > 0 )
              Console::WriteLine("positive");

      if ( myInt < 0 )
            Console::WriteLine ("negative");
  }
};

int main()
{
   mySampleClass^ mySC = gcnew mySampleClass;
   myMethodDelegate^ myD1 = gcnew myMethodDelegate( mySC, &mySampleClass::myStringMethod );
   myD1( 5 );
   IntPtr pint = Marshal::GetFunctionPointerForDelegate(myD1);
   PFUNC pFnc = (PFUNC)pint.ToPointer();
   pFnc(5);  
}
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now