Luavis Kang
Luavis Kang

Reputation: 51

Call C# delegate with function pointer in Managed C++

Program.cs

class Program
    {
        public static void He(string v)
        {
                Console.WriteLine(v);
                Console.WriteLine("End?");
            }
        public delegate void he(string v);

        static void Main(string[] args)
        {
            Class1 cls = new Class1();
            IntPtr p = Marshal.GetFunctionPointerForDelegate(new he(He));
            cls.call(p, "String");
        }
    }

TestClassLibrary.h

namespace TestClassLibrary 
{
    typedef void (Hello)(System::String ^ v);

    public ref class Class1
    {
        public:
        void call(IntPtr p,System::String ^v);
    };
}

TestClassLibrary.cpp

namespace TestClassLibrary 
{
    void Class1::call(IntPtr p,System::String ^ v)
    {
        Hello * h = (Hello *)p.ToPointer();
        h(v);
    }
}

I do not know what is wrong with this code :(

(Test Class Library is compiled to managed DLL.)

Upvotes: 0

Views: 835

Answers (1)

Dave Doknjas
Dave Doknjas

Reputation: 6542

Managed C++/CLI has delegates - the syntax is nearly identical to C# - why not use them instead and no marshalling is involved (since you're compiling to managed C++/CLI anyway).

Upvotes: 1

Related Questions