gpt4 book ai didi

c# - 附加信息 : Attempted to read or write protected memory. 这通常表示其他内存已损坏

转载 作者:行者123 更新时间:2023-11-28 06:45:39 25 4
gpt4 key购买 nike

我正在尝试将字节数组传递给 C++ dll:

C++:

extern "C" __declspec(dllexport) char* myfunction(byte bytes[])
{
char *byteschar = (char*)bytes;
//do somethings with it
return byteschar;
}

c#:

[DllImport("mydll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl
,CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string myfunction(byte[] bytes);

但是当我调用 myfunction 时,我得到了一个 System.AccessViolationException

当我在没有调试器的情况下运行可执行文件时,它似乎工作正常

最佳答案

如果您希望在 C# 中分配缓冲区并在 C++ 中填充,则方法略有不同。

您应该分配一种“非托管”缓冲区,传递给 DLL,然后转换结果并释放缓冲区。它与 C 中的方式完全相同,但从托管环境调用。

你的 C++ 代码应该是这样的:

extern "C" __declspec(dllexport) void myfunction(char* buffer, int length)
{
//Fill buffer with something observing the maximum length of the buffer.
}

C# 中 DLL 的签名应该是:

[DllImport("mydll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl
,CharSet = CharSet.Ansi)]
public static extern string myfunction(IntPtr buffer, Int32 length);

要从 C# 调用它,您应该这样做:

    IntPtr unmanagedBuffer = Marshal.AllocHGlobal(100);
// Your Unmanaged Call
myfunction(unmanagedBbuffer, 100);
string yourString = Marshal.PtrToStringUni(unmanagedBuffer);
Marshal.FreeHGlobal(unmanagedBuffer);

如果您不想在您的应用程序中发生内存泄漏,请不要忘记调用 FreeHGlobal。在“try/finally”子句中保护这一点很有趣。

其他观察是字符串的编码。 Uni,意为统一码。如果您使用其他字符串表示形式,请检查等效的 PtrToStringXXX 函数。

关于c# - 附加信息 : Attempted to read or write protected memory. 这通常表示其他内存已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25050850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com