I have a C# class and an unmanaged C++ class. I want them to
communicate with each other. (through function calls).
To achieve this, I create a managed C++ Wrapper class that takes a
delegate from the C# class, and try to convert it to a pure C++
function pointer, so that the Unmanaged C++ class can call C# code.
Here is what my managed C++ class looks like:
public __delegate void DelegateType(int);
typedef (*FunctionPtr)(int);
public __gc class MyClass1
{
public:
DelegateType * myDelegate;
FunctionPtr myFunctionPtr;
void SetDelegate(DelegateType * d)
{
myDelegate = d;
IntPtr temp;
temp = d->Method->MethodHandle.GetFunctionPointer();
myFunctionPtr = (FunctionPtr) temp.ToPointer();
}
void CallDelegate()
{
myDelegate(10);
}
void CallFunction()
{
myFunctionPtr(30);
}
};
and the C# class looks like this:
class Class2
{
void SampleFunction(int count)
{
for (int i = 0; i < count; i++)
Console.WriteLine("Sample function called " + i);
}
[STAThread]
static void Main(string[] args)
{
Class2 c2 = new Class2();
MyClass1 m = new MyClass1(); // managed C++ class
m.SetDelegate(new DelegateType(c2.SampleFunction));
m.CallDelegate();
m.CallFunction();
}
};
The results:
the first call "m.CallDelegate" works fine, the C# function is called
properly with parameter 10, and the console looks like:
Sample function called 0
Sample function called 1
...
Sample function called 9
as it should look.
The second call "m.CallFunction" also works, since it actually calls c#
code. This means that my conversion from delegate to IntPtr and then to
function pointer works somewhat fine.
The problem is that the parameter is not passed properly.
It seems like there is garbage in the parameter. It should be 30, but
it is actually a large number, so the console looks like
Sample function called 0
Sample function called 1
...
Sample function called 52145
Sample function called 52146
Sample function called 52147
Sample function called 52148
....
and the for loop keeps going.
So, My question is How to properly convert from a delegate to the c++
function pointer (or at least from IntPtr to function pointer)?
Thanks in advance for helping.
Mattias Sj?gren - 19 Jan 2005 21:38 GMT
I'd recommend that you don't try to pass the delegate target address
directly to the native C++ code, but instead write the callback
function in your C++ code and pass a pointer to that. Your C++
callback function can then forward the call to the delegate. The
technique is sort of demonstrated here
http://www.codeproject.com/managedcpp/cbwijw.asp
Mattias

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.