将char* 从C#项目传递到dll函数

8wigbo56  于 2023-10-16  发布在  C#
关注(0)|答案(1)|浏览(168)

我在Visual Studio C++ dll项目中导出了函数:

  1. extern "C" int _stdcall init(char* buff, const char* aData)

在C#中声明:

  1. [DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
  2. public static extern int init(StringBuilder buff, StringBuilder aData);

并从C#应用程序调用它

  1. StringBuilder sResult = new StringBuilder(1024);
  2. last_res = DllApi.init(sResult, new StringBuilder(File.ReadAllText("aaaaaaa")));

得到异常:

  1. Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'xxxxx::init' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling

我的申报有什么问题吗?

30byixjq

30byixjq1#

你的C++函数定义非常清楚地表明调用约定是StdCall,这是DllImport上的默认设置,所以不要设置它。
另外,第二个参数不需要StringBuilder,因为它是const

  1. [DllImport("mydll.dll", CharSet = CharSet.Ansi)]
  2. public static extern int init(StringBuilder buff, string aData);

相关问题