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, t开发者_运维技巧he issue was resolved.
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);
You could add the MarshalAsAttribute
like e.g.
[DllImport("foo.dll")]
protected static extern void Load(
[MarshalAs(UnmanagedType.LPStr)]string filename);
You can pass one of the UnmanagedType
enumeration values to the MarshalAsAttribute
constructor.
See also this overview article over at Code Project.
精彩评论