0

I have this code wrapper, being build as a dll.

namespace VoxelEditor
{
  using namespace System;
  public ref class name
  {

  private: VoxelEngine::test::name* _name;

  public: 
    name()
    {
      _name = new VoxelEngine::test::name; 
    }

    ~name()
    { 
      delete _name;
    }

  void test(IntPtr result, int a, int b)
  { 
    _name->test((int*)result.ToPointer(), a, b); 
  }

  };
}

namespace VoxelEngine
{
  namespace test
  {


    void name::test(int*result, int a, int b)
    {
      *result = a + b;
    }

  }
}

I want to create this name class in c# and call the function test. I read it somewhere I should use IntPtr

int d = 0; 
test.test(d, i, b);
Console.WriteLine(d);

question 1: It crashes, said that the "An exception of type 'SYstem.NullReferenceExeption' occured

question 2: What if a function returns a pointer? I have read this: https://msdn.microsoft.com/en-us/library/367eeye0.aspx And found some answers. But I don't get it. I am new on this.

1
  • You should pass d as ref. Commented Apr 26, 2015 at 14:38

1 Answer 1

2

Pass the argument by reference instead so the C# code can simply use ref d in the method call. A stable copy of it is required so you can pass a pointer to the native code. Like this:

  void test(int% result, int a, int b) { 
      int copy = result;
      _name->test(&copy, a, b); 
      result = copy;
  }

Also note that you must implement the finalizer so you don't leak memory when the C# programmer forgets to dispose the object. It also never hurts to ensure that nothing goes wrong when the C# program disposes more than once:

    ~name() {
        if (_name != nullptr) {
            this->!name();
            _name = nullptr;
        }
    }
    !name() { 
      delete _name;
    }

Your 2nd question is very broad, you'd generally pass such a pointer to the constructor of the ref class that wraps the underlying object. And return a reference to it.

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

Comments

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.