Search code examples
c#c++pointersinteroppinvoke

C# P/Invoke: native output parameter value won't reach managed code


I'm marshalling a native C++ DLL to a C# DLL. I'm not very acknowledged in C/C++, but I've managed to make it work until I got stuck on this problem. Here's a very simplistic code example:

C++

PROASADLL __declspec(dllexport) void outTest(int* number){
    int temp = *number + 10;
    number = &temp; //*number = 12
}

C#

[DllImport("ProAsaNativeDll.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void outTest(ref int number);

public static int OutTest()
{
    int number = 2;
    outTest(ref number);
    return number; //number = 2
}

Please notice that I'm my real scenario, I'm trying to get this to work with a pointer to pointer to struct but I decided to leave it out as it is not a marshalling issue; not even this simple code will work. The C++ code works but I wouldn't rule out being dumb and having a problem there: like I said, I don't know much C/C++.

The number variable value in the C# wrapper method won't change. Please help.


Solution

  • I think you are getting a bad result because in your C++ code you are actually changing the parameter number by setting it to another pointer.

    I believe that your change will only be visible in your function outTest's scope.

    However, if you change the value where the pointer ... points... that's should be a different story. Pretty much like this:

    *number = *number + 10;
    

    EDIT: This bit is not tested. Oh... and also... I haven't written anything in C++ for ages. Might as well be totally wrong.