Gonzalo
Gonzalo

Reputation: 709

Marshalling char *

i have the following method signature on my c++ dll:

extern char *bpStringCalc(char *bpDirectory, char *issString);

And i'm trying to call it from c# using this:

[DllImport(@"C:\MuniAxis\Bp\BpDLL.dll", CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string bpStringCalc([MarshalAs(UnmanagedType.LPStr)] string bpDirectory,
                                         [MarshalAs(UnmanagedType.LPStr)] string issString);

But it keep getting this exception:

'ConsoleApplication1!ConsoleApplication1.Program::bpStringCalc' 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.

Any ideas?

Thanks

Upvotes: 1

Views: 681

Answers (2)

Patko
Patko

Reputation: 4423

Try specifying a Cdecl calling convention on import or __stdcall on export. See this almost similar question.

Upvotes: 4

Billy ONeal
Billy ONeal

Reputation: 106530

Unbalancing the stack probably has more to do with calling convention than it does the actual arguments. C++, by default, uses the __cdecl calling convention. C# defaults to __stdcall because __stdcall is the convention used by Win32. You need to either set calling convention on your import statement in C#, or you need to specify __stdcall in your C++ binary.

EDIT: The above was edited to fix the fact that __cdecl and __stdcall had only one leading underscore each ;)

Upvotes: 4

Related Questions