1

Assume the following:

Let us have a C++ class:

class ExampleClass
{
 private:
    int var1;
 public:
    void DoSomething();
}

Assume also following C++ function which we want to call from .NET Core app with PInvoke or using EmitCalli:

extern "C" ExampleClass CreateObject()

So C++ function returns instance of ExampleClass by value. Is there any way to get this instance on managed part as byte array (assuming that size of ExampleClass is known).

As I remember, in most native x86(x64) calling conventions C++ functions which return structures actully have pointer to the structure to fill as one of the parameters. Will this hint work with NET Core: allocate byte array on managed part and pass pointer as first parameter to unmanaged call?

Thanks!

Gleb Chili
  • 115
  • 3
  • AFAIK you can't use C++ classes from .NET code. If you want to use an instance of that class from C#, one option might be to build a C++/CLI wrapper library that contains a class with the same API as `ExampleClass` and internally calls the C++ function. I'm not sure if C++/CLI works with .NET Core though. – Andy May 03 '19 at 18:08

1 Answers1

1

in C++

ExampleClass CreateClass();

will return a block of bytes of sizeof(ExampleClass) and in absence of virtual members and inheritance it will be plain object and equivalent to same struct definition (see more about this here: Structure of a C++ Object in Memory Vs a Struct )

P/Invoke marshaller should be able to deal with this without a problem.

It it not an IntPtr, it's an actual memory block for C and C++. IntPtr equivalent would be

ExampleClass * CreateClass();

I am not sure why it returns the instance instead of a pointer but they probably had their reasons.

so if you define it

public struct ExampleClass
{
    public int Var1;
}

you should be fine (except if class structure is more complex you would need to check what was layout in C++ compilation, specifically padding. For example class with 2 bools may yield size of 16 in some padding).

see more here:

aiodintsov
  • 2,545
  • 15
  • 17