c# - 尝试读取或写入 protected 内存。这通常表明其他内存已损坏 DllImport

标签 c# c++ file dllimport

我用 C++ 创建了一个 dll。我在该 dll 中有一个函数,其中包含以下代码。

__declspec(dllexport) void MyFunction(CString strPath)
{
    BYTE startBuffer[] = { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0 };
    FILE *f = _wfopen(strPath.GetBuffer(strPath.GetLength()), _T("wb"));        
    if (f != NULL)
    {
        strPath.ReleaseBuffer();
        fwrite(startBuffer, sizeof(startBuffer), 1, f);
        fclose(f);
    }
}

如果我注释掉这一行然后调用dll。不会有任何问题。

调用约定如下:

[DllImport("OutExt.dll",CharSet=CharSet.Unicode)]
static extern void MyFunction([MarshalAs(UnmanagedType.LPStr)] string strPath);

有人请帮我解决这个问题。

最佳答案

CString 是 native C++ 类,无法使用 p/invoke 进行编码。您将需要使用一个指针空终止字符数组。

或者:

__declspec(dllexport) void MyFunction(const char *strPath)

如果您必须限制自己使用遗留的 ANSI 代码页,或者

__declspec(dllexport) void MyFunction(const wchar_t *strPath)

用于 Unicode。

在 C# 端,声明将是:

[DllImport("OutExt.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern void MyFunction(string strPath);

[DllImport("OutExt.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
static extern void MyFunction(string strPath);

分别。

关于c# - 尝试读取或写入 protected 内存。这通常表明其他内存已损坏 DllImport,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938414/

相关文章:

php - 如何使用 PHP 向任何文件添加数字签名(RSA、证书等)?

c# - 是否可以在将在 Linux 中运行的 .Net Core 控制台应用程序中使用 .Net Framework 4.5 Dll 引用

c++ - 改变QDir::rootPath() 为程序运行路径?

c++ - 在没有虚拟原型(prototype)的情况下调用继承类的一种方法

c++ - 如何正确链接静态类

file - 如何在 Windows 7 上的 GitBash 中使用 CLI 在其默认程序中打开文件?

javascript - 如何从打开文件对话框中读取 txt 并使用 javascript (jquery) 将内容加载到文本区域中?

c# - 使用 C# 或在 C# 中的 native C++ 性能

c# - MVC4 按主机名 bundle

c# - 将文件复制到不同的目录