User720153
User720153

Reputation: 139

Made IntPtr from myStruct in c#, but c++ dll is expecting a myStruct*, not an IntPtr

In my c# main, I did

        myStruct ret_vals;
        IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(ret_vals));

        Marshal.StructureToPtr(ret_vals, ptr, false);

MyStruct has a pointer to another structure in it. According to Intelllisense (compile error) my C++ dll's function is expecting a pointer to MyStruct, not an IntPtr. The following won't compile

       DoAT.atClass1 cl = new DoAT.atClass1();

      cl.read_file( ptr);

Incidentally, my c++ function is declared as

    public ref class atClass1
{
    public:
          int read_file(MyStruct & ret_vals)    ;

};

Advice appreciated.

Upvotes: 0

Views: 167

Answers (1)

antonijn
antonijn

Reputation: 5760

You shouldn't use & when using references in C++/CLI, like you would in regular C++, but rather %. This means you'll have to define your C++/CLI function as such:

public ref class atClass1
{
public:
    int read_file(MyStruct % ret_vals);
};

That way you can just call your function using .NET reference parameters:

DoAT.atClass1 cl = new DoAT.atClass1();
cl.read_file(ref ret_vals);

No need for the Marshal class!

Upvotes: 2

Related Questions