Solved

Convert delegate to function pointer in Visual Studio 2005

Posted on 2006-07-18
1
325 Views
Last Modified: 2008-02-01
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
Comment
Question by:james567
1 Comment
 
LVL 15

Accepted Solution

by:
lakshman_ce earned 500 total points
ID: 17135441
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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The following diagram presents a diamond class hierarchy: As depicted, diamond inheritance denotes when two classes (e.g., CDerived1 and CDerived2), separately extending a common base class (e.g., CBase), are sub classed simultaneously by a fourt…
In Easy String Encryption Using CryptoAPI in C++ (http://www.experts-exchange.com/viewArticle.jsp?aid=1193) I described how to encrypt text and recommended that the encrypted text be stored as a series of hexadecimal digits -- because cyphertext may…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question