Search code examples
c#pinvokemarshalling

How should I specify the P/invoke interface for this code?


In C++ I have some code that requires a const char * to be passed in:

void Load(const char *filename)

If I try using String as MSDN seems to suggest:

[DllImport("foo.dll")]
protected static extern void Load(String filename);

I end up getting an exception stating that the call has an unbalanced stack, due to a mismatch between the managed P/Invoke call and the actual C++ function signature.

What would be the appropriate C# function signature I would need to use? I've tried googling for the answer but I'm not coming up with anything.


The solution: It turns out that the reason why I was getting an "unbalanced stack" error was because the test code I was running called for a file that didn't actually exist in the directory. With CallingConvention=cdecl, and the file in the appropriate place, the issue was resolved.


Solution

  • The problem is the calling convention. And while we're at it, you probably need to specify the character set since it may assume Unicode otherwise:

    [DllImport("foo.dll", CharSet:=CharSet.Ansi, CallingConvention:=CallingConvention.Cdecl)]
    protected static extern void Load(String filename);