0

Is this list correct?

unsigned int(c) -> uint(c#)
const char*(c) -> String(c#)
unsigned int*(c) -> uint[](c#)
unsigned char*(c) -> byte[](c#)

I think there's a mistake here because with these 4 parameters for native function I have PInvokeStackImbalance.

C function is:

bool something
  (unsigned char *a,
   unsigned int a_length,
   unsigned char *b,
   unsigned int *b_length);

PInvoke is:

[DllImport(@"lib.dll", EntryPoint = "something")]<br>
public static extern bool something(
    byte[] a,
    uint a_length,
    byte[] b,
    uint[] b_length);
5
  • why last char* is byte ? and can you share your pinvoke ? Commented Jun 8, 2011 at 7:24
  • last unsigned char* because of this stackoverflow.com/questions/4837561/unsigned-char-pointer-in-c Commented Jun 8, 2011 at 7:28
  • 1
    You should post the C function prototype and the C# P/Invoke signature so that we can see what you're talking about. Commented Jun 8, 2011 at 7:31
  • Just show your code and native function declaration. Commented Jun 8, 2011 at 7:32
  • 1
    For the second parameter, it makes sense to marshal it as a null-terminated string (MarshalAs(UnmanagedType.LPStr) attribute), but you should make sure that last two parameters are actually arrays and not simply references (because you will have to know array sizes in order to allocate them on the managed size, before marshaling). Posting both signatures and explaining what the method does will help a lot. Commented Jun 8, 2011 at 7:40

1 Answer 1

2

First, PInvoke.net is your friend.

Second, You conversions are correct except that you should use a StringBuilder for functions that take a char* as a buffer to fill ([in out]).

Your stack imbalance may be due to the use of different calling conventions. The default calling convention for C# is __stdcall, but your C function is probably __cdecl. If that is the case you will need to add the CallingConvention to your DLLImport attribute.

EDIT: Also, as Groo pointed out, if the pointer arguments in your C function are actually just pointers to unsigned int (for example, as opposed to expecting an array of int) then you should use ref uint instead of an int[].

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

1 Comment

I added CallingConvention = CallingConvention.Cdecl and now it works fine. However, I still feel anxious. Anyway, thanks.

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.