3

I want to pass an array/vector/buffer of bytes from c++ to c#

On the c++ side I will have some data in a vector:

std::vector<unsigned char> pixels_cpp;

On the c# side I want to access these data in a byte array, e.g.

byte[] pixels_cs
// or as a MemoryStream object, accompanied with size information.

I am currently using this concept for passing strings from c++ to c#:

void MyWrapper::setSomeString(const std::string& someString)
{
    mono_thread_attach (mono_get_root_domain ());
    MonoMethod* mmSetSomeString = searchMethod("SetSomeString", monoClass);
    void *args [1];
    args [0] = mono_string_new (domain, someString.c_str());
    MonoObject *result = mono_runtime_invoke (mmSetSomeString, CsClassInstance, args, NULL);
    // check result
}

And the c# signature that is called is:

public bool SetSomeString(string someString)

How does this look like if I want to pass a vector of bytes?

  • How do I allocate the memory and fill it with data from pixels_cpp?
  • How to I invoke the call with mono_runtime_invoke (or equivalent)?
  • How should the c# method signature look like?

1 Answer 1

1

The solution is to use mono_array_new. Example:

void MyWrapper::setVector(std::vector<uint8_t>& data)
{
    mono_thread_attach (mono_get_root_domain ());
    MonoMethod* mmSetVector = searchMethod("SetVector", monoClass);

    void *args [1];
    MonoArray *data  = mono_array_new(domain, mono_get_byte_class(), data.size());

    for (auto i=0; i<data.size(); i++) {
        mono_array_set (data, uint8_t, i, data[i]);
    }

    args [0] = data;

    MonoObject *result = mono_runtime_invoke (mmSetVector, CsClassInstance, args, NULL);
    // check result
}
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.