0

I'm struggling with the following design issue:

There is a C-Function

void Foo(uint8_t *data, uint32_t length);

Which I want to use in C#. So I create the delegate:

public delegate void Foo_Fcn([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)]byte[] data, UInt32 length);
public Foo_Fcn Foo;

So, the (I admit: in fact minor) problem here is: I have to pass this second argument in my C# code:

byte[] data = /*...*/;
Foo(data, (UInt32)data.Length);

This seems a bit redundant, I'd prefer to call

byte[] data = /*...*/;
Foo(data);

Is this in any way achievable (without using a 'proxy function')? If yes: How?

4
  • 3
    No, there isn't. You will need either to create a method in-between that figures out the details necessary for the C-function, or just pass the length. Commented Mar 17, 2015 at 20:21
  • That's unfortunate, do you mind posting it as an answer so I can accept it for future answer-seekers? Commented Mar 17, 2015 at 20:30
  • 3
    The C function needs that length; how do you think it would be possible for your delegate to automatically figure out that it needed to pass the first argument’s length there? It’s you who has to provide that detail. Commented Mar 17, 2015 at 20:31
  • I just thought: The Marshalling is smart enough to create an for example 2 Byte array and hoped I can also pass the ArraySize implicitly some similar way...e.g. public delegate void Foo_Fcn([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)]byte[] data, [ParamIndex=0, ParamProperty=Length]); or however you can coat it in syntactic sugar. Commented Mar 17, 2015 at 20:39

1 Answer 1

2

Unfortunately there is no way to automagically do this.

Your best option (in my opinion) would be to wrap the C-function in a .NET class that hides these details internally. This would also make it easier to handle future changes to the external API or possibly even change it completely, without the rest of the code having to change.

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.