473,799 Members | 3,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing none static member function as callback parameter to manag

Hi,

I have my main application class(unmanaged ) that has a none static member
function that I need to pass as a delegate to managed C# method.

In one of the methods of this class(unmamange d), I am calling a managed C#
method(I use gcnew to instantiate the managed class). One of the parameters
of this C# method is a delegate. I need to pass the none static member
function as a delegate(functi on pointer) as a parameter in the managed C#
function call.

e.g.

//Managed C#
namespace MySpace
{
public delegate int MyDelegate();

MyDelegate rDelegate;

public class Managed
{
void ManagedFunction (MyDelegate del)
{
//do stuff
}

}
}
//Unmanaged C++ written in VC++ 6.0

//.h
class Unmanaged
{
public:
Unmanaged();
~Unmanaged();

void UnmanagedFunc1( );
void UnmanagedFunc2( );

}

*.cpp
using namespace MySpace;

void Unmanaged::Unma nagedFunc1()
{
MySpace::Manage d ^man = gcnew MySpace::Manage d;

//I need to pass UnmanagedFunc2( ) here as a delegate/callback as a
//parameter to ManagedFunction .
man->ManagedFunctio n(??)

}

void Unmanaged::Unma nagedFunc2()
{

}

Will appreciate all the help I can get on this.

Also what if I need to pass a string also as a parameter to
ManagedFunction (). In unmanaged it is a char* or a CString. How can I do the
conversion to pass it to managed.

Thanks for the help.

Aug 17 '06
12 11371
Hi Tamas,

Sorry for the confusion. Actually the code was originally written in VC++6
and it has been ported to .Net 2005 and compiled as C++/CLI and it is talking
to a managed C# application(dll ). I dont think you need to have an
intermediate dll in such a case. All I want to do is pass a function
pointer/delegate with a CString/char * parameter to managed C# function(one
of the parameters of the C# function is a delegate).

Im able to pass the delegate to managed C# function but cant pass the
CString/char * parameter(which is a parameter of this delegate).

Will appreciate your help.
THanks

"Tamas Demjen" wrote:
Haxan wrote:
Actually the unmanaged class is part of an old dll that was written using
VC++ 6.0. Since we later on started using managed code, the changes have to
be part of the dll.

You have to write a mixed-mode DLL, a translation layer between the C#
and the VC6 code. That mixed-mode DLL has to export native functions
that your VC6 code can call. In turn, it will internally set up the
managed event forwarder and calls the managed library function. This
intermediate DLL is necessary, because I don't think you can compile
C++/CLI code from VC6.

Tom
Aug 21 '06 #11
Haxan wrote:
Im able to pass the delegate to managed C# function but cant pass the
CString/char * parameter(which is a parameter of this delegate).
OK, I modified my original example to pass a String instead of an int.
It also includes the String^ to const char* conversion. I don't see it
happening without an intermediate forwarder, which I called Thunk. It
can go to the C++/CLI DLL. In your case ManagedSender is written in C#,
but it shouldn't make any difference. The point is that ManagedSender
doesn't know anything about the receiver, it has no idea that it's
handled by an unmanaged class.

This is the best I can do to help you. I can't suggest anything that
automatically marshals the string without the intermediate Thunk object.
There may be something available that I'm not aware of.

Tom

#include "stdafx.h"
#include <vcclr.h>
#include <iostream>

using namespace System;

////////////////////////////////////////////
// C# DLL

#pragma managed

public delegate void ManagedEvent(St ring^ arg);

public ref class ManagedSender
// event sender
{
public:
event ManagedEvent^ SomeEvent;
void FireEvent()
{
SomeEvent("Hell o");
}
};

////////////////////////////////////////////
// Mixed native C++ / C++/CLI DLL

#pragma unmanaged

class UnmanagedReceiv er
{
public:
void HandleEvent(con st char* arg)
{
std::cout << arg << "\n";
}
};

#pragma managed

struct StringConvAnsi
{
char *szAnsi;
StringConvAnsi( String^ s)
: szAnsi(static_c ast<char*>(
Runtime::Intero pServices::Mars hal::StringToHG lobalAnsi(s).
ToPointer()))
{
}
~StringConvAnsi ()
{
Runtime::Intero pServices::Mars hal::FreeHGloba l(IntPtr(szAnsi ));
}
char* c_str() const
{
return szAnsi;
}

};

ref class Thunk
// event forwarder
{
public:
Thunk(Unmanaged Receiver* A_ptr) : ptr(A_ptr) { }
void CallbackForward er(String^ arg)
{
ptr->HandleEvent(St ringConvAnsi(ar g).c_str());
}
private:
UnmanagedReceiv er* ptr;
};

////////////////////////////////////////////
// Test application to set up the chain of calls

#pragma managed

int main(array<Stri ng ^^args)
{
UnmanagedReceiv er receiver;
ManagedSender^ sender = gcnew ManagedSender;
Thunk^ thunk = gcnew Thunk(&receiver );
sender->SomeEvent += gcnew ManagedEvent(th unk,
&Thunk::Callbac kForwarder);
sender->FireEvent();
return 0;
}
Aug 21 '06 #12
Thanks Tom,

That was really helpful. Appreciate that.

"Tamas Demjen" wrote:
Haxan wrote:
Im able to pass the delegate to managed C# function but cant pass the
CString/char * parameter(which is a parameter of this delegate).

OK, I modified my original example to pass a String instead of an int.
It also includes the String^ to const char* conversion. I don't see it
happening without an intermediate forwarder, which I called Thunk. It
can go to the C++/CLI DLL. In your case ManagedSender is written in C#,
but it shouldn't make any difference. The point is that ManagedSender
doesn't know anything about the receiver, it has no idea that it's
handled by an unmanaged class.

This is the best I can do to help you. I can't suggest anything that
automatically marshals the string without the intermediate Thunk object.
There may be something available that I'm not aware of.

Tom

#include "stdafx.h"
#include <vcclr.h>
#include <iostream>

using namespace System;

////////////////////////////////////////////
// C# DLL

#pragma managed

public delegate void ManagedEvent(St ring^ arg);

public ref class ManagedSender
// event sender
{
public:
event ManagedEvent^ SomeEvent;
void FireEvent()
{
SomeEvent("Hell o");
}
};

////////////////////////////////////////////
// Mixed native C++ / C++/CLI DLL

#pragma unmanaged

class UnmanagedReceiv er
{
public:
void HandleEvent(con st char* arg)
{
std::cout << arg << "\n";
}
};

#pragma managed

struct StringConvAnsi
{
char *szAnsi;
StringConvAnsi( String^ s)
: szAnsi(static_c ast<char*>(
Runtime::Intero pServices::Mars hal::StringToHG lobalAnsi(s).
ToPointer()))
{
}
~StringConvAnsi ()
{
Runtime::Intero pServices::Mars hal::FreeHGloba l(IntPtr(szAnsi ));
}
char* c_str() const
{
return szAnsi;
}

};

ref class Thunk
// event forwarder
{
public:
Thunk(Unmanaged Receiver* A_ptr) : ptr(A_ptr) { }
void CallbackForward er(String^ arg)
{
ptr->HandleEvent(St ringConvAnsi(ar g).c_str());
}
private:
UnmanagedReceiv er* ptr;
};

////////////////////////////////////////////
// Test application to set up the chain of calls

#pragma managed

int main(array<Stri ng ^^args)
{
UnmanagedReceiv er receiver;
ManagedSender^ sender = gcnew ManagedSender;
Thunk^ thunk = gcnew Thunk(&receiver );
sender->SomeEvent += gcnew ManagedEvent(th unk,
&Thunk::Callbac kForwarder);
sender->FireEvent();
return 0;
}
Aug 23 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2497
by: Steven T. Hatton | last post by:
I am trying to convert some basic OpenGL code to an OO form. This is the C version of the program: http://www.opengl.org/resources/code/basics/redbook/double.c You can see what my current effort at converting that code to an OO form looks like in the code listed below. The problem I'm running into is that the OpenGL functions that take the names of other functions as arguments don't like the way I'm passing the member functions of my...
4
2383
by: Morgan Cheng | last post by:
I tried to build a CThread on linux which imitate the behavior of java Thread. I think this is still in the scope of C++. First, I tried this way #include <pthread.h> class CThread { public: void start(); void run();
6
8831
by: keepyourstupidspam | last post by:
Hi, I want to pass a function pointer that is a class member. This is the fn I want to pass the function pointer into: int Scheduler::Add(const unsigned long timeout, void* pFunction, void* pParam)
0
3291
by: Jeffrey B. Holtz | last post by:
Has anyone used the multimedia timere timeSetEvent in C#? I'm trying to use it to get a 1ms accurate timer. All the other implementations are far to inaccurate in their resolution. 1ms Timer = 0ms.....60ms. I'm already timing the callbacks using the Win32API QueryPerformanceCounter/Frequency. The code I have is actually performing the callback and it looks like it is close to 1ms but I now need to get my object passed to this static...
3
3069
by: ryan.mitchley | last post by:
Hi all I have a class (cPort) that is designed to receive objects and, depending on the type, call a handler (callback) in any descendant of a cProcessBlock class. Callback functions take a shared_ptr<cBaseas a parameter, and return void. The code was working fine, although I have encountered problems (under a Microsoft compiler, of course - VC 8.0) when I attempt to add callbacks to a class with multiple inheritance. I hate multiple
4
5903
by: Jimmy | last post by:
I need to use Asynchronous Socket functions in a server application and am learning from sources such as the MSDN2 (http://msdn2.microsoft.com/en-us/library/bbx2eya8.aspx). What I observed is that all callback handlers in examples are static functions. I did try non-static callback handlers; they certainly works, and they usually make my code simpler. For example, a typical tutorial will start an asynchronous connection with:
6
7684
by: smmk25 | last post by:
Before I state the problem, I just want to let the readers know, I am knew to C++\CLI and interop so please forgive any newbie questions. I have a huge C library which I want to be able to use in a .NET application and thus am looking into writing a managed C++ wrapper for in vs2005. Furthermore, this library has many callback hooks which need to be implemented by the C++ wrapper. These callback functions are declared as "extern C...
2
4130
by: Evan Burkitt | last post by:
Hi, all. I have a Windows DLL that exports a number of functions. These functions expect to receive a pointer to a callback function and an opaque void* parameter. The callback functions are typedef'd to take void* parameters, through which the DLL's function passes its void* parameter to the callback function. This allows me to use class instances as callback handlers, as in the example below. //Executable and DLL know this:
8
1973
by: Neviton | last post by:
Is it possible ? There is any work around? Thanx
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10491
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10268
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10247
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10031
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9079
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.