3

I know only very little about C++/CLI, but I have a simple problem that needs a solution. I have a C++/CLI class method that takes a byte-array as a parameter. The array is of a pre-determined length, and can be allocated in C# beforehand. The array is supposed to be filled with data by the C++/CLI method.

How do I declare the method and then call it from C#?

I tried something like having the following in my C++/CLI class:

public ref class C
{
public:
    void FillBytes(array<BYTE^>^ bytes);
};

And then, in C#:

o = new C();
var bytes = new byte[3];
o.FillBytes(bytes);

But that didn't work at all :).

1
  • I made a typo at first, when I wrote array<BOOL^>^ instead of array<BYTE^>^ Commented Apr 12, 2010 at 17:43

2 Answers 2

10

I know this question was asked a long time ago but hopefully it will help someone else who is checking this post. From C++/CLI you need to send this:

void FillBytes(array<unsigned char>^% bytes);

The "hat" means its a CLR type and the % means you will pass it by reference so that the C++/CLI fills the array.

Then you can call it from C# like this:

o = new C();
var bytes = new byte[3];
o.FillBytes(ref bytes);

Hope it helps someone!

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

1 Comment

How would you change this for a dynamic array?
9

Have you tried using byte instead of a BOOL reference?

void FillBytes(array<System::Byte>^ bytes);
                                ↑
                           //   no ^ here

1 Comment

Oops, I just typed in some simplified version of my actual code and made a typo. But the problem still remains. I get "Argument '1': cannot convert from 'byte[]' to 'System.ValueType[]'", when trying to compile the above code.

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.