1

I have some C code which will be called from C# using P/Invoke. I have a C struct member for which I am trying to define an C# equivalent.

Array16 *data;

Array16 is defined as

typedef unsigned char Array16[16];

How do I define the C# equivalent of this C data member?

6
  • Declare it as IntPtr and marshal the payload by hand. Commented Oct 29, 2012 at 19:35
  • Depends. Do you need to access the data in the ptr? Use byte*. You don't? use IntPtr. Commented Oct 29, 2012 at 19:38
  • @David - how do I marshal by hand? Commented Oct 29, 2012 at 19:46
  • @KendallFrey byte* requires unsafe code. No need for that. Commented Oct 29, 2012 at 19:50
  • How do you marshal by hand? That depends. Is the data being passed to the native code? Or is it being returned by the native code? The answer to the question you actually asked is, IntPtr, but you'll need more. In short, your question lacks some essential detail. Commented Oct 29, 2012 at 19:51

2 Answers 2

1

I guess your C struct looks something like this:

struct MyStruct {
   Array16 *data;
};

Because of the reference to the payload, I don't believe you can get the p/invoke marshaler to do the work for you. You'll need to marshal by hand.

In the C# code declare the struct like this

[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    IntPtr data;
}

When you need to prepare such a struct for a function call do this:

MyStruct s;
s.data = Marshal.AllocHGlobal(16);
byte[] bytes = Encoding.Default.GetBytes("some string data");
Marshal.Copy(bytes, 0, s.data, Math.Min(16, bytes.Length));

If you need to read data that is returned by your function, use the same tactic in the opposite direction.

int nbytes = ... // probably returned by the function, no more than 16
byte[] bytes = new bytes[nbytes];
Marshal.Copy(s.data, bytes, 0, nbytes);
string returnedString = Encoding.Default.GetString(bytes);

When you have finished with the struct make sure you deallocate the memory by calling

Marshal.FreeHGlobal(s.data);
Sign up to request clarification or add additional context in comments.

Comments

0

The closest type to C++ unsigned char in C# is byte.

2 Comments

how do i achieve the same in my case which is not a simple unsigned char, but a pointer to an unsigned char array?
Whilst that is true it is of no real use here.

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.