1

I'm trying to create a method using mono where a string is passed by reference, here is the test code I have:

C++:

static bool p_TestMethod(int num, MonoString ** response) {

    auto b = mono_string_new(mono_domain_get(), "Test repsonse");
    response = &b;

    return true;
}
//...
mono_add_internal_call("SharpCode.TestClass::Testmethod", p_TestMethod);

C#:

    [MethodImpl(MethodImplOptions.InternalCall)]
    public static extern bool Testmethod(int num, out string response);

    public bool RunTheTest()
    {
        string x;
        Testmethod(0, out x);
        Console.WriteLine("Test: {0}", x);

        return true;
    }

But no response is printed (only Test: )

How do I properly pass a string by reference using Mono?

ikkentim
  • 1,639
  • 15
  • 30
  • Try using the `ref` keyword instead of `out` – Alex Barac Mar 15 '14 at 19:09
  • Regardless of what happens on the Mono side, `response = ...` in the C++ code just alters a local variable, so that can't be right. –  Mar 15 '14 at 19:13
  • @AlexBarac doesn't make a difference. – ikkentim Mar 15 '14 at 19:21
  • @delnan I tried MonoString * response instead of MonoString ** response too, but that didn't work either. I decided to test a double pointer after reading this: https://github.com/mono/mono/blob/master/docs/internal-calls . But yet no result. – ikkentim Mar 15 '14 at 19:23
  • @ikkentim After skimming over that page, I agree that a pointer-to-pointer seems the right parameter type. But that's not what I was trying to say. `response = &b;` is completely conceptually wrong. It does not affect what the parameter points at, it only makes you lose access to what the parameter used to point at; and the address of `b` has an expiration date, it should not outlive the function call. I'd expect `*respone = b;`, though I can **not** vouch for my expectations, as they are solely based on my C++ knowledge. –  Mar 15 '14 at 19:42
  • @delnan My C++ kwowledge is near zero, but thanks a lot! I've fixed the issue by doing *response = mono_string_new(mono_domain_get(), "Test repsonse"); as you suggested – ikkentim Mar 15 '14 at 19:48

1 Answers1

2

Fixed by doing it like this:

*response = mono_string_new(mono_domain_get(), "Test repsonse"); 

as suggested by delnan

Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
ikkentim
  • 1,639
  • 15
  • 30