0

i'm having an issue PInvoking a native function from c++... i have PInvoked all the other native functions without problems (params were very simple conversions). below is the c++ prototype and its usage in c++:

DECL_FOOAPIDLL DWORD WINAPI FOO_Command( VOID *Par, //pointer to the parameter(s) needed by the command DWORD Len, //length of Parameter in bytes DWORD Id //identification number of the command ); 

usage:

static DWORD DoSomething(WCHAR *str) { DWORD len = (wcslen(str)+1)*sizeof(WCHAR); DWORD ret = FOO_Command((VOID *)str,len,FOOAPI_COMMAND_CLOSE); return(ret); } 

my C# PInvoke:

[DllImport("FOO.dll")] static public extern uint FOO_Command(IntPtr par, uint len, uint id); private void DoSomething() { string text = "this is a test"; IntPtr ptr = Marshal.StringToHGlobalUni(text); uint hr = FOO_Command(ptr,255, FOOAPI_COMMAND_CLOSE); Marshal.FreeHGlobal(ptr); } 

1) is this the correct way to PInvoke this API? 2) how can i get the size of ptr where i have 255 as the parm?

the above does work, but i'm new to PInvoke and the "Native" world...

Thank you

3
  • You're lying about your string length -- it's obviously shorter than 127 characters -- but it's otherwise correct as long as the DECL_FOOAPIDLL macro specifies the __stdcall calling convention. Commented Jun 29, 2012 at 19:16
  • What's the issue you are experiencing? Commented Jun 29, 2012 at 19:20
  • I wasnt sure if i could set the PInvoke c# api up better so that i didnt need to marshal the string to a pointer... But after some research i assume its the only way seeing how the pointer will need to be destroyed after use... Should i use Marshal.sizeof(ptr) to get the correct length of the string? I tried simply (text.length+1) but only half of the string was recieved by the c++ api....??? Commented Jun 29, 2012 at 23:20

1 Answer 1

1
private void DoSomething() { string text = "this is a test"; IntPtr ptr = Marshal.StringToHGlobalUni(text); uint hr = FOO_Command(ptr, (text.Length + 1) * 2, FOOAPI_COMMAND_CLOSE); Marshal.FreeHGlobal(ptr); } 
Sign up to request clarification or add additional context in comments.

1 Comment

The *2 is to account for the fact that a UTF-16 character unit is 2 bytes wide. The C++ code uses *sizeof(WCHAR) to achieve the same effect.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.