3

I am trying to call an existing C dll from a C# application, using System.Runtime.InteropServices, and am having difficulty matching the signatures between the PInvoke function and the Target function.

The target function is

__declspec(dllexport) DWORD GetSomeString(char* strOut);

And my PInvoke function is

[DllImport("Existing.dll")]
public static extern uint GetSomeString([MarshalAs(UnmanagedType.LPWStr)]
                            string strDisplay);

I make the function call

string tempStr = "My Output String";
uint retVal = GetSomeString(tempStr);

But I get the message

Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem... ...A call to PInvoke function 'GetSomeString' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

I have also tried implementing the PInvoke function as

[DllImport("Existing.dll")]
public static extern uint GetSomeString([MarshalAs(UnmanagedType.LPWStr)]
                            StringBuilder strDisplay);

But to no avail.

Does anyone out there have an idea what I could be doing wrong?

Please let me know if further info is required or my question is unclear.

Thanks in advance.

2 Answers 2

4

You need to specify the calling convention. By default, PInvoke uses StdCall, but your method is (likely) Cdecl.

[DllImport("Existing.dll", CallingConvention=CallingConvention.Cdecl)]
Sign up to request clarification or add additional context in comments.

Comments

2

In addition to the incorrect calling convention mentioned by Reed Copsey, the matching type for char* is UnmanagedType.LPStr.

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.