C# 发生了 System.AccessViolationException

高新娥 2010-04-09 12:03:56
在C#中调用c++写的dll,而dll里面有一个加密函数指针和一个解密函数指针
我在c#中的代码如下
[DllImport("Kernel32.dll")]
//加载dll
public static extern IntPtr LoadLibrary(string dllfile);

[DllImport("Kernel32.dll")]
//获取dll的函数指针
public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);

[DllImport("kernel32.dll", EntryPoint = "FreeLibrary", SetLastError = true)]
//释放dll
public static extern bool FreeLibrary(IntPtr hModule);

//定义委托
public delegate int encry(string gy,string sy,string zz, ref string dd);

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
IntPtr hinst = LoadLibrary("IEncryptionandDecryption.dll");

IntPtr proc = GetProcAddress(hinst, "Encryption");

encry en = Marshal.GetDelegateForFunctionPointer(proc, typeof(encry)) as encry;

string username = "8596586";

en("fakdkafakfdansf", "dkkdkdlfslkfs", "fsfasfsafa", ref username);

FreeLibrary(hinst);

}
但是一运行就会报 发生了 System.AccessViolationException 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。这个错误,这是什么原因啊?
...全文
1941 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
高新娥 2010-04-10
  • 打赏
  • 举报
回复
呵呵,谢谢,问题已经解决了,修改了dll里的参数类型
xingyuebuyu 2010-04-09
  • 打赏
  • 举报
回复
//定义委托
public delegate int encry(string gy,string sy,string zz, System.Test.StringBuilder dd);


IntPtr hinst = LoadLibrary("IEncryptionandDecryption.dll");

IntPtr proc = GetProcAddress(hinst, "Encryption");

encry en = Marshal.GetDelegateForFunctionPointer(proc, typeof(encry)) as encry;

StringBuilder username = new StringBuilder(256);
username.Append("8596586");

en("fakdkafakfdansf", "dkkdkdlfslkfs", "fsfasfsafa",username);

FreeLibrary(hinst);


用StringBuilder代替string
Peter200694013 2010-04-09
  • 打赏
  • 举报
回复
尝试读取或写入受保护的内存: 应该是因为你的指针指向了受保护的内存,然后在程序中又对其进行了读或写操作。

110,537

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧