首页 > 解决方案 > 如何使用从 C# 代码传递到 C++ 代码 (dll) 的字符串并带有 AccessViolationException

问题描述

我正在尝试将我的 c# 程序中的字符串传递给我创建的 c++ DLL。每当我尝试使用该字符串时,我的程序都会抛出 System.AccessViolationException: 'Attempted to read or write protected memory。这通常表明其他内存已损坏'

我已经能够将其他变量类型(如 int 和 double)从我的 C# 代码传递到我的 C++ 代码并使用它们,但是传递字符串会不断抛出 AccessViolationException。

System.Runtime.InteropServices;

Class Program{
  [DllImport("myDll", SetLastError = true)]
  static extern bool test(string data);
  static void Main(string[] args)
  {
   test("Hello world");
  }
  extern "C" __declspec(dllexport) void test(string *data)
  {
  // I get an error whenever I asing *data to s;
  string s = *data;
  }

我希望将 data 中的值分配给 s (在我的 c++ 代码中),而不会在运行时抛出 System.AccessViolationException 错误

标签: c#c++dll

解决方案


推荐阅读