Search code examples
c#c++interopc++-cli

System::IntPtr to int* in C++/CLI


I am trying to call an existing C++ library from a C# application using the C++/CLI interop layer. I have a C++ function that looks something like this:

void doSomething(int* foo, int size);

And a C# object that holds two fields, an IntPtr start, and an int size. I wrote a managed C++ class that looks like this:

public ref class Wrapper {
public:
    void run(System::IntPtr itn, int size);
};

And now I want to call doSomething in Wrapper::run, and have doSomething have access to the same block of data that the C# object points to. Is what I'm trying to do possible without a copy, and if so, how?


Solution

  • To call doSomething from Wrapper::run, try casting the return of System::IntPtr::ToPointer, like so:

    doSomething(reinterpret_cast<int*>(itn.ToPointer()), size);