c# - DLLImport get Attempted to read or write protected 内存

标签 c# delphi pinvoke dllimport

我要疯了。

我有一个 dll,有这个功能:

function MyFunc(myId: integer; var LstCB: array of char): integer; stdcall;

第一个参数是一个糟糕的整数。 但是第二个是一个 char[2048],它会变成这样

('9', #13, #10, '8', '8', '8', '8', '0', '0', '0', '0', '0', '0', '0', '0', '2', '5', '0', '7', #13, #10, '8', '8', '8', '8', '0', '0', '0', '0', '0', '0', '0', '0', '2', '6', '0',  #13, #10, '8', '8', '8', '8', '0', '0', '0', '0', '0', '0', '0', '0', '3', '3', '1', '5', #13, #10, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0, #0,....#0)

我用 DllImport 导入了这个:

[DllImport(@"MyDll.dll", EntryPoint = "MyFunc", CallingConvention = CallingConvention.StdCall)]
internal static extern int MyFunc(int myId, string list);

然后我得到:

Attempted to read or write protected memory. This is often an indication that other memory has been corrupted.

请问您有什么想法吗???

谢谢。

最佳答案

您的 Delphi 函数正在为字符串参数使用一个开放数组。这不是应该跨 DLL 边界公开的内容。调用 Delphi 开放数组的协议(protocol)是特定于实现的。

您应该更改您的 Delphi 代码以接收 PChar

function MyFunc(myId: Integer; LstCB: PChar): Integer; stdcall;

如果数据从 C# 传递到 Delphi DLL,那么您的 P/invoke 没问题。如果 DLL 旨在将数据返回到 C# 代码,那么您需要在 P/invoke 中将文本参数声明为 StringBuilder

[DllImport(@"MyDll.dll", EntryPoint = "MyFunc", CallingConvention = CallingConvention.StdCall)]
internal static extern int MyFunc(int myId, StringBuilder list);
...
StringBuilder list = new StringBuilder(2048);
int res = MyFunc(ID, list);
string theList = list.ToString();

唯一需要注意的是 char 在 Delphi 中的含义。如果 DLL 是使用 Delphi 2009 或更高版本构建的,则 char 是 Unicode 字符,您需要在 P/invoke 中指定 CharSet

关于c# - DLLImport get Attempted to read or write protected 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7662940/

相关文章:

javascript - 如何解决 Aspx.cs 中文本框的问题

c# - 具有公共(public)无参数构造函数的 Object 类有什么好处?

delphi - 具有匿名方法的 VCL 事件 - 您对此实现有何看法?

delphi - DUnit: 'Global' 设置和拆卸

c++ - 反向 P/调用教程?

c# - List<T>.ToList() 是否枚举集合

Delphi如何完全删除代码完成?

c# - 通过 P/Invoke 使用回调和堆对象的安全方法

c# - 与顺序和显式相比,StructLayout.Auto 意味着什么?

c# - WebClient 抛出 "No Data Available for Encoding 1252"