Skip to main content
 首页 » 编程设计

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

2024年02月23日14mq0036

我要疯了。

我有一个 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。