0

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.

1
  • 2
    It is bad C++ code. That never gets better when you pinvoke it. Make it work from a C++ test program first. Commented Mar 23, 2016 at 18:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Like riding a bike
@Jacobr365 Yeah... All's well and neat... Until you fall down and "bend" your nose :)
Nice! Like I said, C++ isn't my forte, but I see both "what you did there" and where I was wrong. Many thanks!
@S.O. That's how we all learn... Keep up the good work! Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.