
Dispatch tables with functions containing managed pointers
Jonathan,
It didn't last long!
As soon as there is a managed pointer in the class it
breaks again!
Try this:
#using <mscorlib.dll>
using namespace System::Runtime::InteropServices;
[ StructLayout(Sequential) ]
__gc class Managed
{
public:
int I;
Managed *Next;
Quote:
};
int Func(Managed *M)
{
return M->I;
Quote:
}
class CallBack
{
public:
int (*foo)(Managed *);
Quote:
} CB;
int _tmain(void)
{
Managed *MP=new Managed();
MP->I=2;
MP->Next=NULL;
CB.foo=Func;
int J=CB.foo(MP);
return 0;
Quote:
}
And you get this:
An unhandled exception of type 'System.TypeLoadException'
occurred in Test.exe
Additional information: Can not marshal field Next of type
Managed: This type can not be marshaled as a structure
field.
Bummer!
Quote:
>-----Original Message-----
>I'm not 100% certain why this works: but if you change
the definition of
>Managed to:
>using namespace System::Runtime::InteropServices;
>[ StructLayout(Sequential) ]
>__gc class Managed {
>public:
> int I;
>};
>then your code compiles and run correctly.
>--
>Jonathan Caves
>Microsoft Corporation
>This posting is provided "AS IS" with no warranties, and
confers no rights.
>You assume all risk for your use. ? 2002 Microsoft
Corporation. All rights
Quote:
>reserved.
>http://www.microsoft.com/info/cpyright.htm.
>> How do I construct a dispatch table containing function
>> pointers that point to members of unmanaged objects, or
>> are normal functions? It is a requirement that the
>> functions accept at least one argument that is a pointer
>> to a managed object.
>> The following program illustrates the problem:
>> #using <mscorlib.dll>
>> #include <tchar.h>
>> using namespace System;
>> __gc class Managed
>> {
>> public:
>> int I;
>> };
>> int Func(Managed *M)
>> {
>> return M->I;
>> }
>> class CallBack
>> {
>> public:
>> int (*foo)(Managed *);
>> } CB;
>> int _tmain(void)
>> {
>> Managed *MP=new Managed();
>> MP->I=2;
>> CB.foo=Func;
>> int J=CB.foo(MP);
>> return 0;
>> }
>> The program throws an exception on the line
>> containing "int J=CB.foo(MP);" complaining that it
cannot
>> marshal parameter #1, because the type definition
contains
>> no layout information.
>> The only soution I have found is to use delegates, but
>> this will require a massive set of changes to the
>> application because delegates must point to managed
object
>> members only.
>> Thanks/Anker
>.